So far in my attempts, I'm able to draw lines on a plain image, Like create my own plain context of CGRect size and draw lines on it. All the tutorials I see is how to draw on a created image context of x*y size. But I would like to draw lines on an already present image context like a picture of a dog and make some drawings. But so far I'm not getting results I look for. This is the code I tested with, without assigning the image, i'm able to get a line draw. But with import of image, I do not get the desired line on the picture.
let myImage = UIImage(named: "hqdefault.jpg")!
let myRGBA = RGBAImage(image: myImage)!
UIGraphicsBeginImageContextWithOptions(CGSize(width: rgbaImage.width, height: rgbaImage.height), false, 0)
let context:CGContextRef = UIGraphicsGetCurrentContext()!
CGContextMoveToPoint(context, CGFloat(100.0), CGFloat(100.0))
CGContextAddLineToPoint(context, CGFloat(150.0), CGFloat(150.0))
CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor)
CGContextStrokePath(context)
let image = UIGraphicsGetImageFromCurrentImageContext()
CGContextRestoreState(context)
UIGraphicsEndImageContext()
//: Return image
let view = UIImageView.init(image: image)
view.setNeedsDisplay()
These are the lines I wrote to draw a line inside an image and return it's context. I am not able to pick the imported picture context or draw lines if I try to , as it returns nil in the end. I couldn't figure out my mistake so far. Can you suggest how to draw a simple line on a picture in image view ?
Can you suggest how to draw a simple line on a picture in image view
Sure. Make an image context. Draw the image view's image into the context. Draw the line into the context. Extract the resulting image from the context and close the context. Assign the extracted image to the image view.
Example:
let im = self.iv.image! // iv is the image view
UIGraphicsBeginImageContextWithOptions(im.size, true, 0)
im.drawAtPoint(CGPointMake(0,0))
let p = UIBezierPath()
p.moveToPoint(CGPointMake(CGFloat(100.0), CGFloat(100.0)))
p.addLineToPoint(CGPointMake(CGFloat(150.0), CGFloat(150.0)))
p.stroke()
self.iv.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
Before:
After:
In the second image, notice the line running from (100,100) to (150,150).