因此,您有一個像灰色東西一樣圖像的圖層,您將此圖像(在本例中是一個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