2011-06-06 47 views
1

我在单独的UIImageView中有背景图像(ImageBG)和前景图像(ImageFG)。它们的大小相同,顾名思义,ImageBG位于ImageFG后面,因此您无法看到ImageBG。用触摸绘制和擦除线条

如果用户开始“画”他们,而不是一条线出现在用户触摸屏幕的地方,我希望这部分ImageFG变得透明并显示ImageBG。

我能想到的最接近的事情就是从零开始。

我知道如何在图形上下文中绘制图形,但是当我画一条透明线(alpha = 0)时,好......我在图形上下文中获得了一条透明线,基本上没有任何绘制。这是我用来设置笔触颜色。

CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 0.0) 

我在做什么错?我知道这是可能的,因为有应用程序在那里做。

任何提示,技巧或方向表示赞赏。

回答

10

因此,您有一个像灰色东西一样图像的图层,您将此图像(在本例中是一个UIImageView及其UIImage.image的scratchImage)写入图形上下文。然后,将混合模式设置为kCGBlendModeClear,然后保存该图像(使用清除的路径)。这会在另一个UIImageView中显示一个图像。请注意,在这个例子中,self是一个UIView。

所以touchesMoved之外创建一个变量的touchesBegan举行CGPoint

CGPoint previousPoint; 
CGPoint currentPoint; 

然后,将其设置为上一个点。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
UITouch *touch = [touches anyObject]; 

previousPoint = [touch locationInView:self]; 

}

在touchesMoved,写入图像的上下文中,行程与透明掺合物的模式的图像,从上下文保存图像,和前一个点设置为当前点。

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



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

UIGraphicsBeginImageContext(self.frame.size); 
//This may not be necessary if you are just erasing, in my case I am 
//adding lines repeatedly to an image so you may want to experiment with moving 
//this to touchesBegan or something. Which of course would also require the begin 
//graphics context etc. 

[scratchImage.image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; 

CGContextSaveGState(UIGraphicsGetCurrentContext()); 
CGContextSetShouldAntialias(UIGraphicsGetCurrentContext(), YES); 
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); 
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0); 
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.25, 0.25, 0.25, 1.0); 
CGMutablePathRef path = CGPathCreateMutable(); 
CGPathMoveToPoint(path, nil, previousPoint.x, previousPoint.y); 
CGPathAddLineToPoint(path, nil, currentPoint.x, currentPoint.y); 
CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeClear);  
CGContextAddPath(UIGraphicsGetCurrentContext(), path); 
CGContextStrokePath(UIGraphicsGetCurrentContext()); 
scratchImage.image = UIGraphicsGetImageFromCurrentImageContext(); 
CGContextRestoreGState(UIGraphicsGetCurrentContext()); 
UIGraphicsEndImageContext(); 
previousPoint = currentPoint; 
} 
+3

对您有帮助吗?如果确实如此,如果你接受它会很好,这样其他人就可以判断它是否是正确的答案。 – cdasher 2011-09-06 10:03:55

+0

这将擦除图像视图中的实际图像,而不是绘制在其上的图形。 – Shailesh 2014-10-05 19:22:12

相关问题