使用CGContext(alpha + blend)绘制干净,流畅的自由手绘图

时间:2012-09-27 05:47:05

标签: iphone objective-c ios cocoa-touch uiimage

以下是我使用CGContext进行免费手绘的代码。我想使用alpha值为0.6的颜色和混合模式为kCGBlendModeColor。但是在绘图时,我得到以下效果:颜色重叠并变暗。我想要不重叠和平滑的画。

 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
  {

   UITouch *touch = [touches anyObject];
   lastTouch = [touch locationInView:self];
 }

 -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint   currentTouch = [touch locationInView:self];

CGFloat brushSize = 35;

UIColor *color = [UIColor blueColor];
CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0;

if ([color respondsToSelector:@selector(getRed:green:blue:alpha:)]) {
    [color getRed:&red green:&green blue:&blue alpha:&alpha];
} else {
    const CGFloat *components = CGColorGetComponents(color.CGColor);
    red = components[0];
    green = components[1];
    blue = components[2];
    alpha = components[3];
}

UIGraphicsBeginImageContext(self.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, brushSize);

CGContextSetRGBStrokeColor(context, red, green, blue, 0.6) ;
CGContextSetBlendMode(context, kCGBlendModeColor);

CGContextBeginPath(context);
CGContextMoveToPoint(context, lastTouch.x, lastTouch.y);
CGContextAddLineToPoint(context, currentTouch.x, currentTouch.y);
CGContextStrokePath(context);
self.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
lastTouch = [touch locationInView:self];

 }

enter image description here

2 个答案:

答案 0 :(得分:1)

如果你真的想要绘制干净,流畅的自由手绘图,使用OpenGL,我也使用过它,非常好。

点击此链接

http://developer.apple.com/library/ios/#samplecode/GLPaint/Introduction/Intro.html

希望这可以帮助你:)

答案 1 :(得分:0)

这可能不是您想要做的,但一个可能的解决方案是将完整的alpha绘制到您创建的“额外”子视图中,然后将其alpha值设置为.6。

换句话说,使用1.0 alpha绘制,但在alpha值为.6的视图中绘制。

当您在保留所需的Alpha效果的同时在上一个绘图上方进行着色时,这应该可以防止出现可见效果。

祝你好运!希望有所帮助。

相关问题