objective-c - 触摸绘制和删除线条

标签 objective-c cocoa-touch ios

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

如果用户开始在其上“绘制”,而不是在用户触摸屏幕的地方出现线条,我希望ImageFG的该部分变得透明并显示ImageBG。

我能想到的最接近的是刮刮取胜。

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

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

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

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

最佳答案

因此,您有一个层,该层是一些像要刮掉的灰色东西一样的图像,您可以将此图像(在本示例中为UIImageView及其UIImage .image)写入图形上下文。然后,将混合模式设置为kCGBlendModeClear对其进行描边,然后保存该图像(具有清除的路径)。这将显示您可能在另一个UIImageView中的图像。请注意,在这种情况下,self是UIView。

因此,在touchesMoved外部创建了一个变量来保存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;
}

关于objective-c - 触摸绘制和删除线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6255901/

相关文章:

ios - 消除 UITableView 下面多余的分隔符

ios - 如何在 XCode 4.2 中编辑 Settings.bundle

ios - 当 View Controller 在本地显示并显示警报时,控件不会变暗

ios - 在带有IOS 6的iPad上展示aN操作表时崩溃

objective-c - 以编程方式向 nsview 添加关闭按钮

ios - UITextfield 限制汉字长度

ios - 使用自动布局、IB 和字体大小时,表头 View 高度错误

ios - 我如何从 NSString 获取类?

objective-c - 是否可以在 objective-c 中使用 YouTubePlayer-Swift?

objective-c - 如何淡化 NSSound 对象