swiftdrawingcore-animationcashapelayer

Eraser functionality for CAShapelayer drawings : SWIFT


I am working on drawing app. I want to implement eraser functionality that erases the path drawn using UIBezierPath.Is it possible??

I have tried below code but its not working

    UIGraphicsBeginImageContextWithOptions(self.tempImageView.frame.size, false, 0.0)
    if let context = UIGraphicsGetCurrentContext()
    {
        tempImageView.image?.draw(in: CGRect(x:
            0, y: 0, width: self.tempImageView.frame.size.width, height: self.tempImageView.frame.size.height))
        let sublayer = CAShapeLayer()
        self.tempImageView.layer.addSublayer(sublayer)
        context.setBlendMode(CGBlendMode.clear)
        sublayer.strokeColor = editorPanelView.drawingColor.cgColor
        sublayer.lineJoin = kCALineJoinRound
        sublayer.lineCap = kCALineCapRound
        sublayer.lineWidth = editorPanelView.brushWidth
        let path = UIBezierPath()
        path.move(to: CGPoint(x: mid1.x, y: mid1.y))
        path.addQuadCurve(to:CGPoint(x:mid2.x, y:mid2.y) , controlPoint: CGPoint(x: prevPoint1.x, y: prevPoint1.y))
        sublayer.path = path.cgPath
        layerArray.append(sublayer)
        UIGraphicsEndImageContext()
    }

I am not able to find any solution for this. Any help (even if it's just a kick in the right direction) would be appreciated.


Solution

  • A CAShapeLayer is a vector drawing. It's shapes. The usual eraser tool works with raster (pixel-based) drawings. The two are different, and there isn't a straightforward way to do an eraser tool on vector drawings.

    One way you could do it is to have the eraser tool edit a mask layer which is applied to your shape layer. It would have the effect of erasing the parts of the shape layer where the mask is opaque.

    One tricky part to this is that once you've drawn into the mask, you'd have to erase that part of the mask in order for the user to be able to draw new content into the erased area, and that might cause the erased parts of the old drawing to show through.

    Getting what you want to do to work well would be quite tricky.