画一条线,就像橡皮擦 Swift3

Jon*_*ett 2 swift swift3

我正在制作一个简单的绘图程序,在 UIView 中绘制一些线条(下面代码中的画布)。这工作正常。

现在我希望能够像橡皮擦一样擦掉这些线条。

我不只是想在它上面绘制白色,因为画布视图后面有一个用户可以更改的背景图像,因此将背景图像绘制到视图中也不起作用,因为他们可以在绘制过程中进行更改。

如何在所有现有路径上绘制一条像橡皮擦一样的路径?

这是我当前的绘图代码

func drawLine(fromPoint start: CGPoint, toPoint end:CGPoint, color: UIColor, width: CGFloat, canvas: UIView) 
{
    let line = CAShapeLayer()
    let linePath = UIBezierPath()

    linePath.move(to: start)
    linePath.addLine(to: end)

    line.path = linePath.cgPath
    line.strokeColor = color.cgColor
    line.lineWidth = width
    line.lineJoin = kCALineJoinRound

    canvas.layer.addSublayer(line)
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Jon*_*ett 7

好的,我已经弄清楚了。而不是使用 CAShapeLayers 创建它需要在图形上下文中绘制的路径。这是我现在使用的代码。canvas 现在是 UIImageView 而不是 UIView。

func drawLine(fromPoint start: CGPoint, toPoint end:CGPoint, color: UIColor, width: CGFloat)
{
    //get the current graphics context based on the frame of the view I want to draw in.
    UIGraphicsBeginImageContextWithOptions(canvas.frame.size, false, 0.0);

    //draw the current image (all the lines drawn so far) into the view so we aren't just drawing new lines each time and losing the old ones
    canvas.image?.draw(in: canvas.bounds)
    //FYI - canvas is defined at the top of the class as a UIImageView

    //get the current graphics context
    if let context = UIGraphicsGetCurrentContext()
    {
        //set line color and other properties
        context.setLineWidth(width)
        context.setStrokeColor(color.cgColor)
        context.setLineCap(CGLineCap.round)

        //add the line itself
        context.move(to: start)
        context.addLine(to: end)

        //this is a check to see if the last component of the color is 0 which means the color is transparent, if it is, we use CGBlendMode.clear which acts like an eraser. you could have a toggle for this instead if you like but I decided to set the color to one without alpha as the way of setting the eraser.
        if(currentColor.cgColor.components?.count == 4 && currentColor.cgColor.components?.last == 0)
        {
            context.setBlendMode(CGBlendMode.clear)
        }
        else
        {
            context.setBlendMode(CGBlendMode.normal)
        }


        //stroke the path so it actually appears
        context.strokePath()

        //set the canvas image to the new image we just created
        canvas.image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

    }


}
Run Code Online (Sandbox Code Playgroud)