用触摸绘制和擦除线条

Rob*_*rto 1 cocoa-touch objective-c ios

我在单独的UIImageViews中有一个背景图像(ImageBG)和一个前景图像(ImageFG).它们的大小相同,顾名思义,ImageBG落后于ImageFG,因此您无法看到ImageBG.

如果用户开始"绘制"它们,而不是出现用户触摸屏幕的线条,我希望ImageFG的那部分变得透明并显示ImageBG.

我能想到的最接近的事情是划伤和胜利.

我知道如何在图形上下文中进行绘制,但是当我绘制一条透明线(alpha = 0)时,嗯......我在我的图形上下文中的任何内容上都有一条透明线,所以基本上没有绘制任何内容.这是我用来设置笔触颜色的方法.

CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 0.0)
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我知道这是可能的,因为那里有应用程序可以做到这一点.

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

cda*_*her 10

所以你有一个图像就像你想要刮掉的灰色图像,你将这个图像(在这个例子中是scratchImage,它是一个UIImageView及其UIImage .image)写入图形上下文.然后使用设置为kCGBlendModeClear的混合模式对其进行描边,然后保存该图像(使用已清除的路径).这将显示您在另一个UIImageView下面的图像.请注意,在这个例子中,self是一个UIView.

所以外部touchesMoved创建一个变量来保存CGPoint

CGPoint previousPoint;
CGPoint currentPoint;
Run Code Online (Sandbox Code Playgroud)

然后在touchesBegan中,将其设置为上一点.

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

previousPoint = [touch locationInView:self];
Run Code Online (Sandbox Code Playgroud)

}

在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;
}
Run Code Online (Sandbox Code Playgroud)

  • 这有帮助吗?如果确实如此,如果您接受它会很好,以便其他人可以判断它是否是正确的答案. (3认同)