绘制一条行像橡皮擦Swift3

时间:2017-08-25 10:18:38

标签: 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)
}

谢谢!

2 个答案:

答案 0 :(得分:2)

你可以使用模式CGBlendMode.clear的笔划进行擦除和 绘图的CGBlendMode.normal

tmp

答案 1 :(得分:2)

好的,我已经弄明白了。而不是使用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()

    }


}