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 (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...