Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I draw on an image in Swift?

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.

like image 357
caleb Avatar asked Oct 10 '16 01:10

caleb


People also ask

How do you draw a line in Swift?

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 .


1 Answers

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:

Swift 4

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 } 
like image 58
Jorge Ramírez Avatar answered Sep 21 '22 17:09

Jorge Ramírez