2

我想完成一个功能,就像一个画笔。手指滑动区域变为透明,边框逐渐变化。

在此处输入图像描述
我现在只能使用以下代码将颜色更改为晶莹剔透:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if(self.eraser) return;

CGFloat scale = self.transform.a;
if (scale < 1) scale = 1;

CGPoint p = [[touches anyObject] locationInView: self];
CGPoint q = [[touches anyObject] previousLocationInView: self];

UIImage* image;
image = self.image;
CGSize  size = self.frame.size;
UIGraphicsBeginImageContext(size);
CGRect  rect;
rect.origin = CGPointZero;
rect.size = size;
[image drawInRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineCap(context, kCGLineCapRound);

CGContextBeginPath(context);
CGContextSaveGState( context );
CGContextSetLineWidth(context, (10.0 / scale) + 1);
CGContextSetBlendMode(context, kCGBlendModeClear);

CGContextMoveToPoint(context, q.x, q.y);
CGContextAddLineToPoint(context, p.x, p.y);
CGContextStrokePath(context);
CGContextRestoreGState( context );

UIImage* editedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self setBounds:rect];
[self setImage:editedImage];

}

如何通过逐渐变化获得优势?提前致谢。

4

1 回答 1

4

kCGBlendModeDestinationIn您可以通过在用户通过的每个点的模式中绘制具有可变 alpha 的径向渐变来实现此效果。

这种混合模式的效果是只将图层的 alpha 应用到下面的图层。通过我们渐变的变量 alpha,我们可以实现这个效果。

const CGFloat kBrushSize = 10.f;

CGContextSaveGState(context);

// Make a radial gradient that goes from transparent black on the inside
// to opaque back on the outside.
size_t num_locations = 2;
CGFloat locations[2] = { 0.0, 1.0 };
CGFloat components[8] = { 1.0, 1.0, 1.0, 0.0,
                          1.0, 1.0, 1.0, 1.0 };

CGColorSpaceRef myColorspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
CGGradientRef myGradient = CGGradientCreateWithColorComponents (myColorspace, components,
                                                                locations, num_locations);
CGColorSpaceRelease(myColorspace);

// Draw the gradient at the point using kCGBlendModeDestinationIn
// This mode only applies the new layer's alpha to the lower layer.
CGContextSetBlendMode(context, kCGBlendModeDestinationIn);
CGContextDrawRadialGradient(context, myGradient, p, 0.f, p, (kBrushSize / scale) + 1, kCGGradientDrawsAfterEndLocation);

CGGradientRelease(myGradient);

CGContextRestoreGState(context);

这是此代码的屏幕截图:

CGBrush 涂鸦

注意:使用此技术,如果用户非常快速地移动他/她的手指,您可能会看到离散的画笔点可见的间距效果。这是一些绘图软件的功能,但如果您不希望这样做,您可以添加代码以在当前和上一个之间插入点以绘制更多画笔点,从而创建更连续的笔触。

此外,您应该能够调整渐变色标以实现您喜欢的任何类型的笔刷柔和度。

来源:https ://developer.apple.com/library/mac/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_shadings/dq_shadings.html

于 2016-04-20T03:33:20.743 回答