【发布时间】:2019-05-08 08:50:35
【问题描述】:
我需要像上图那样在 UIImage 中画/涂鸦一条线,我看到很多教程在 UIView 上涂鸦线,但在 UIImage 中没有。
用户在图像上涂鸦后,我想将其保存为新图像(有线条的图像)。我如何在 Swift 中做到这一点?
我只能在 UIView 上找到画线,而不是在 UIImage 中 UIView 上的绘图就像这个 youtube 教程 http://youtube.com/watch?v=gbFHqHHApC4 中的这个,我将其更改为继承 DrawView 到 UIImageView
struct Stroke {
let startPoint : CGPoint
let endPoint : CGPoint
let strokeColor : CGColor
}
class DrawView : UIImageView {
var isDrawing = false
var lastPoint : CGPoint!
var strokeColor : CGColor! = UIColor.black.cgColor
var strokes = [Stroke]()
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard !isDrawing else { return }
isDrawing = true
guard let touch = touches.first else {return}
let currentPoint = touch.location(in: self)
lastPoint = currentPoint
print(currentPoint)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard isDrawing else { return}
guard let touch = touches.first else {return}
let currentPoint = touch.location(in: self)
let stroke = Stroke(startPoint: lastPoint, endPoint: currentPoint, strokeColor: strokeColor)
strokes.append(stroke)
lastPoint = currentPoint
setNeedsDisplay()
print(currentPoint)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard isDrawing else { return}
isDrawing = false
guard let touch = touches.first else {return}
let currentPoint = touch.location(in: self)
let stroke = Stroke(startPoint: lastPoint, endPoint: currentPoint, strokeColor: strokeColor)
strokes.append(stroke)
setNeedsDisplay()
lastPoint = nil
print(currentPoint)
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
context?.setLineWidth(5)
context?.setLineCap(.round)
for stroke in strokes {
context?.beginPath()
context?.move(to: stroke.startPoint)
context?.addLine(to: stroke.endPoint)
context?.setStrokeColor(stroke.strokeColor)
context?.strokePath()
}
}
func erase() {
strokes = []
strokeColor = UIColor.black.cgColor
setNeedsDisplay()
}
}
我已将情节提要中的 UIImage 指定为使用自定义类“DrawView”,就像我上面的代码一样,但我不知道为什么这些线条没有出现在我的 UIImage 上
【问题讨论】:
-
尝试使用 2 张图片。
-
尝试使用 2 个图像 1. 包含当前绘制的临时图像 2. 包含其他已创建图像的主图像
-
你有没有尝试过?如果是,请显示代码以及什么不起作用。
-
在
imageView上画线并从中捕获新图像? -
是的,我需要类似@TheTiger 的东西