我需要像上面的图片一样在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上
3 回答
详情
Xcode 9.3,Swift 4.1
解决方案
用法
将DrawingImageView添加到根(父)视图(触摸绘图将自动启用)
要保存UIImage,请使用
drawingImageView.screenShot
完整样本
结果
您可以将
UIImageView
放在后台,将UIView
放在其顶部,然后将UIView
捕获为图像并合并它 .请参考此捕获UIView:How to capture UIView to UIImage without loss of quality on retina display
然后使用以下方法合并它:
这可能对你有所帮助 . 请参阅链接
How do I draw on an image in Swift?
制作图像图形上下文 . (在iOS 10之前,您可以通过调用UIGraphicsBeginImageContextWithOptions来完成此操作 . 在iOS 10中,还有另一种方法,UIGraphicsImageRenderer,但如果您不想使用它,则不必使用它 . )
将图像绘制(即复制)到上下文中 . (对于这个目的,UIImage实际上有绘制...方法 . )
在上下文中绘制线条 . (这里有CGContext函数 . )
从上下文中提取生成的图像 . (例如,如果您使用了UIGraphicsBeginImageContextWithOptions,则可以使用UIGraphicsGetImageFromCurrentImageContext . )然后关闭上下文 .