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.
To draw a line from the current point to a specific point, you call the addLine(to:) method. By default, iOS fills the path with the default foreground color, which is black. To fill it with a different color, you can use the .
All you need to do is create and get an Image Context object and access all its powerful 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:
func drawOnImage(_ image: UIImage) -> UIImage { // Create a context of the starting image size and set it as the current one UIGraphicsBeginImageContext(image.size) // Draw the starting image in the current context as background image.draw(at: CGPoint.zero) // Get the current context let context = UIGraphicsGetCurrentContext()! // Draw a red line context.setLineWidth(2.0) context.setStrokeColor(UIColor.red.cgColor) context.move(to: CGPoint(x: 100, y: 100)) context.addLine(to: CGPoint(x: 200, y: 200)) context.strokePath() // Draw a transparent green Circle context.setStrokeColor(UIColor.green.cgColor) context.setAlpha(0.5) context.setLineWidth(10.0) context.addEllipse(in: CGRect(x: 100, y: 100, width: 100, height: 100)) context.drawPath(using: .stroke) // or .fillStroke if need filling // Save the context as a new UIImage let myImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // Return modified image return myImage }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With