微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

CGContext 如何知道 UIImage 的来源?

如何解决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()

有什么想法吗?你能介绍一篇文章让我理解这个逻辑吗?

ps。 Here 是上面代码的结果。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。