I need to be able to programmatically draw on an image, and save that image for later use. Say, draw a line on specific x and y coordinates on the image, save the image, and display it onto a simple view controller. How would I go about doing this in Swift? (Preferably Swift 2, I am still in development and haven't updated my mac to Sierra)
Update: Possibly something to do with converting a UIImage to a CGLayer, drawing on it, and then converting it back to a UIImage.
相关问题
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- State preservation and restoration strategies with
- “Zero out” sensitive String data in Swift
- SwiftUI: UIImage (QRCode) does not load after call
相关文章
- 现在使用swift开发ios应用好还是swift?
- UITableView dragging distance with UIRefreshContro
- Using if let syntax in switch statement
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- xcode 4 garbage collection removed?
- Xcode: Is there a way to change line spacing (UI L
- Unable to process app at this time due to a genera
Since iOS 10 you can use the UIGraphicImageRenderer, which has a better syntax and has some great features!
Swift 4
All you need to do is create and get an Image Context object and acess all its powerfull drawing methods. You can learn more about the CGContext object features here.
This function draws a line and a circle on an UIImage and returns the modified image:
Swift 4
Updated Answer: Once you get the From and To coordinates, here is how to draw a line in a UIImage with those coordinates. From and To coordinates are in image pixels.
Details
Xcode 9.1, Swift 4
Solution
Images samples
Parent Image:
Child Image:
Usage example 1
Result 1
Usage example 2
Result 2
Usage example 3
Result 3
Full sample code
It's simple:
Make an image graphics context. (Before iOS 10, you would do this by calling
UIGraphicsBeginImageContextWithOptions
. In iOS 10 there's another way, UIGraphicsImageRenderer, but you don't have to use it if you don't want to.)Draw (i.e. copy) the image into the context. (UIImage actually has
draw...
methods for this very purpose.)Draw your line into the context. (There are CGContext functions for this.)
Extract the resulting image from the context. (For example, if you used
UIGraphicsBeginImageContextWithOptions
, you would useUIGraphicsGetImageFromCurrentImageContext
.) Then close the context.