ios 如何清除uiview上使用触摸点绘制的线条

webghufk  于 2023-02-14  发布在  iOS
关注(0)|答案(2)|浏览(186)

我的工作要求,我需要画线的UIImageView沿着触摸点。我需要清除所有的图纸从UIImageView的按钮点击。我可以画线,但不能清除线的按钮点击。我甚至想实现清除所有和撤消选项了。有人能请指导我的方式,我可以实现清除所有和撤消选项。下面是我用来实现绘图的代码。不知道如何实现清除所有和撤消绘图。

UITouch *touch = [touches anyObject];

CGPoint currentPoint = [touch locationInView:_selectedImageView];

 _ctx = UIGraphicsGetCurrentContext();

CGContextSaveGState(_ctx);

UIGraphicsBeginImageContext(self.view.frame.size);
[self.selectedImageView.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), brush );
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), red, green, blue, 1.0);
CGContextSetBlendMode(UIGraphicsGetCurrentContext(),kCGBlendModeNormal);

CGContextStrokePath(UIGraphicsGetCurrentContext());
self.selectedImageView.image = UIGraphicsGetImageFromCurrentImageContext();
[self.selectedImageView setAlpha:opacity];
UIGraphicsEndImageContext();

lastPoint = currentPoint;
xdnvmnnf

xdnvmnnf1#

我能够得到我的问题的解决方案,以清除从下面的例子中画出的点或线。我能够实现全部清除和撤消,通过下面的例子从github.https://github.com/backslash112/paint-with-undo/tree/master

ocebsuys

ocebsuys2#

private func clear(from: CGPoint?, to: CGPoint?, lineWidth: CGFloat = 34) {
    guard let from = from, let to = to, let image = imageView?.image, let size = imageView?.bounds else { return }
                   
    UIGraphicsBeginImageContext(size.size)
    let context = UIGraphicsGetCurrentContext()
    context?.setLineCap(.round)
    context?.setLineWidth(lineWidth)
    context?.setStrokeColor(UIColor.white.cgColor)
    context?.setBlendMode(.clear)
    
    image.draw(in: size)
    
    context?.move(to: from)
    context?.addLine(to: to)
    context?.strokePath()
    
    let newCGImage = context?.makeImage()
    
    UIGraphicsEndImageContext()
    
    if let newCGImage = newCGImage {
        let img = UIImage(cgImage: newCGImage)
        imageView?.image = img
    }
}

相关问题