Swift 画一条像橡皮擦一样的线
我正在制作一个简单的绘图程序,在UIView(下面代码中的画布)中绘制一些线。这个很好用 现在我想能够像橡皮擦一样擦掉这些线 我不想只在它上面画白色,因为在画布视图后面有一个背景图像,用户可以更改,所以将背景图像绘制到视图中也不起作用,因为他们可以在绘制过程中更改一半 如何在所有现有的路径上绘制一个像橡皮擦一样的路径 这是我当前的绘图代码Swift 画一条像橡皮擦一样的线,swift,swift3,Swift,Swift3,我正在制作一个简单的绘图程序,在UIView(下面代码中的画布)中绘制一些线。这个很好用 现在我想能够像橡皮擦一样擦掉这些线 我不想只在它上面画白色,因为在画布视图后面有一个背景图像,用户可以更改,所以将背景图像绘制到视图中也不起作用,因为他们可以在绘制过程中更改一半 如何在所有现有的路径上绘制一个像橡皮擦一样的路径 这是我当前的绘图代码 func drawLine(fromPoint start: CGPoint, toPoint end:CGPoint, color: UIColor, wi
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)
}
谢谢 您可以在CGBlendMode.clear模式下使用笔划进行擦除和删除 用于绘图的CGBlendMode.normal
linePath.stroke(with: CGBlendMode.clear, alpha: 1.0)
好的,我已经弄明白了。而不是使用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()
}
}
你能告诉我如何在我上面的函数中使用它吗?注意:非常确定何时设置t,以及Abdelahd在这里有什么帮助?我想你在这里写的和我需要的差不多,但我想不出来。你能做些什么让它更清楚吗?谢谢