因此,您有一个像灰色东西一样图像的图层,您将此图像(在本例中是一个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;
}
对您有帮助吗?如果确实如此,如果你接受它会很好,这样其他人就可以判断它是否是正确的答案。 – cdasher 2011-09-06 10:03:55
这将擦除图像视图中的实际图像,而不是绘制在其上的图形。 – Shailesh 2014-10-05 19:22:12