简体   繁体   English

iOS Swift - 在 UIImage 上画线以保存到文件

[英]iOS Swift - Draw line on UIImage to save to file

All the iOS drawing information I'm finding is related to how to display things in a view.我发现的所有 iOS 绘图信息都与如何在视图中显示内容有关。 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 本身的信息。

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).具体来说,我希望将图像文件作为 UIImage 打开(已经知道如何执行此操作),在该图像中画一条线,然后将新的 UIImage 保存到一个文件中(也已经知道如何执行此操作)。 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.我猜之前已经回答过类似的问题,但是我在该领域缺乏知识似乎很难正确搜索和找到这些答案。

from & to coordinates are in image pixel units from & to 坐标以图像像素为单位

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
}

you can fine the Objective-c answer Here你可以在这里用 Objective-c 回答

Updated for Swift 4 from answer by Nadeesha Lakmal从 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM