简体   繁体   中英

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. 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.

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.

from & to coordinates are in image pixel units

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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