How do I draw on an image in Swift?

前端 未结 5 1531
深忆病人
深忆病人 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:27

    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.

    func drawLineOnImage(size: CGSize, image: UIImage, from: CGPoint, to: CGPoint) -> UIImage {
    
    // begin a graphics context of sufficient size
    UIGraphicsBeginImageContext(size)
    
    // draw original image into the context
    image.drawAtPoint(CGPointZero)
    
    // get the context for CoreGraphics
    let context = UIGraphicsGetCurrentContext()
    
    // set stroking width and color of the context
    CGContextSetLineWidth(context, 1.0)
    CGContextSetStrokeColorWithColor(context, UIColor.blueColor().CGColor)
    
    // set stroking from & to coordinates of the context
    CGContextMoveToPoint(context, from.x, from.y)
    CGContextAddLineToPoint(context, to.x, to.y)
    
    // apply the stroke to the context
    CGContextStrokePath(context)
    
    // get the image from the graphics context 
    let resultImage = UIGraphicsGetImageFromCurrentImageContext()
    
    // end the graphics context 
    UIGraphicsEndImageContext()
    
    return resultImage }
    

提交回复
热议问题