2017-08-25 78 views
-1

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

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

我不只是想画白,因为用户可以更改画布视图后面有一个背景图像,因此将背景图像绘制到视图中也不起作用,因为它们可以将其更改为一半通过绘图的方式。

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

这里是我当前的绘图代码

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) 
} 

谢谢!

回答

0

可以使用与模式CGBlendMode.clear和中风擦除 CGBlendMode.normal绘制

linePath.stroke(with: CGBlendMode.clear, alpha: 1.0) 
+0

你能展示如何在上面的函数中使用它吗?注意确定何时设置t以及什么 –

+0

Abdelahad在这里有什么帮助?我认为你在这里写的东西接近我需要的东西,但我无法弄清楚。有什么你可以做的更清楚吗?谢谢。 –

0

OK我已经想通了这一点。而不是使用CAShapeLayers来创建它需要在图形上下文中绘制的路径。这里是我现在使用的代码。画布现在是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() 

    } 


}