iOS Swift - 在 UIImage 上画线以保存到文件 [英] iOS Swift - Draw line on UIImage to save to file

查看:37
本文介绍了iOS Swift - 在 UIImage 上画线以保存到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

All the iOS drawing information I'm finding is related to how to display things in a view. Specifically layering different images, rects, or paths in a view to be seen on screen. I'm having trouble finding information as to how I can actually manipulate a UIImage itself.

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

Specifically, I'm looking to open an image file as a UIImage (already know how to do this), draw a line in that image, and then save the new UIImage to a file (already know how to do this as well). I would assume there would be a fairly simple way to do this, but every solution I find seems to be going into a complex solution which seems like overkill for what I assume would be a minor task. How can I go about doing this simply? Or are the much more complex solutions the necessary way?

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

I'm guessing something similar to this has been answered before, but my lack of knowledge in the area seems to be making it difficult to properly search for and find these answers.

推荐答案

从 Nadeesha Lakmal 的回答中为 Swift 4 更新

Updated for Swift 4 from answer by Nadeesha Lakmal

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
}

这篇关于iOS Swift - 在 UIImage 上画线以保存到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆