How do I draw on an image in Swift?

前端 未结 5 1527
深忆病人
深忆病人 2020-12-09 04:18

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

5条回答
  •  天涯浪人
    2020-12-09 04:40

    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
    }
    

提交回复
热议问题