【问题标题】:iOS Swift - Draw line on UIImage to save to fileiOS Swift - 在 UIImage 上画线以保存到文件
【发布时间】:2015-04-01 23:57:56
【问题描述】:

我找到的所有 iOS 绘图信息都与如何在视图中显示事物有关。特别是在屏幕上显示的视图中分层不同的图像、矩形或路径。我无法找到有关如何实际操作 UIImage 本身的信息。

具体来说,我希望将图像文件作为 UIImage 打开(已经知道如何执行此操作),在该图像中画一条线,然后将新的 UIImage 保存到文件中(已经知道如何执行此操作好)。我会假设会有一种相当简单的方法来做到这一点,但我发现的每个解决方案似乎都进入了一个复杂的解决方案,这对于我认为是一项小任务来说似乎有点矫枉过正。我怎样才能简单地做到这一点?或者更复杂的解决方案是必要的方式吗?

我猜以前已经回答过类似的问题,但我在该领域缺乏知识似乎很难正确搜索和找到这些答案。

【问题讨论】:

标签: ios swift uiimage


【解决方案1】:

从和到坐标以图像像素为单位

func drawLineOnImage(size: CGSize, image: UIImage, from: CGPoint, to: CGPoint) -> UIImage {
    UIGraphicsBeginImageContext(size)
    image.drawAtPoint(CGPointZero)
    let context     = UIGraphicsGetCurrentContext()
    CGContextSetLineWidth(context, 1.0)
    CGContextSetStrokeColorWithColor(context, UIColor.blueColor().CGColor)
    CGContextMoveToPoint(context, from.x, from.y)
    CGContextAddLineToPoint(context, to.x, to.y)
    CGContextStrokePath(context)

    let resultImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return resultImage
}

你可以细化 Objective-c 答案Here

【讨论】:

    【解决方案2】:

    根据 Nadeesha Lakmal 的回答为 Swift 4 更新

    func drawLineOnImage(size: CGSize, image: UIImage, from: CGPoint, to: CGPoint) -> UIImage {
        UIGraphicsBeginImageContext(size)
        image.draw(at: CGPoint.zero)
        guard let context = UIGraphicsGetCurrentContext() else { return UIImage() }
        context.setLineWidth(1.0)
        context.setStrokeColor(UIColor.blue.cgColor)
        context.move(to: from)
        context.addLine(to: to)
        context.strokePath()
    
        guard let resultImage = UIGraphicsGetImageFromCurrentImageContext() else { return UIImage() }
        UIGraphicsEndImageContext()
        return resultImage
    }
    

    【讨论】:

    • 请注意,"from" 和 "to" 已经是 CGPoints,所以你不需要将它们解构为 "startPoint" 和 "endPoint"。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 2019-09-25
    • 2021-02-09
    • 2019-01-23
    相关资源
    最近更新 更多