如何解决CGContext 如何知道 UIImage 的来源?
这是我使用的代码的一部分。
class DrawingEditorController: UIViewController {
@IBOutlet weak var canvas: UIImageView!
var lastPoint = CGPoint.zero
var isDrawing = false
func set(_ image: UIImage) {
canvas.image = image
backupImages.append(image)
}
override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?) {
guard let touch = touches.first else { return }
lastPoint = touch.location(in: UIView(frame: canvas.frame.offsetBy(dx: canvas.imageFrame.minX,dy: canvas.imageFrame.minY)))
isDrawing = false
}
override func touchesMoved(_ touches: Set<UITouch>,with event: UIEvent?) {
guard let touch = touches.first else { return }
let currentPoint = touch.location(in: UIView(frame: canvas.frame.offsetBy(dx: canvas.imageFrame.minX,dy: canvas.imageFrame.minY)))
drawLine(from: lastPoint,to: currentPoint)
lastPoint = currentPoint
isDrawing = true
}
override func touchesEnded(_ touches: Set<UITouch>,with event: UIEvent?) {
if !isDrawing {
drawLine(from: lastPoint,to: lastPoint)
}
isDrawing = false
}
func drawLine(from: CGPoint,to: CGPoint) {
UIGraphicsBeginImageContextWithOptions(canvas.imageFrame.size,false,0.0)
guard let context = UIGraphicsGetCurrentContext() else { return }
context.move(to: CGPoint(x: 0,y: 0))
context.addLine(to: to)
context.strokePath()
canvas.image = UIGraphicsGetimageFromCurrentimageContext()
UIGraphicsEndImageContext()
}
}
我只是好奇 drawLine()
方法中发生了什么,特别是关于 CGContext
。
这段代码看起来像 context
知道 canvas.image
的起源一样。它怎么能做到这一点?我所做的只是将大小传递给 UIGraphicsBeginImageContextWithOptions()
。
有什么想法吗?你能介绍一篇文章让我理解这个逻辑吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。