How to draw single line into UIImage using Core Graphics framework? Recently I needed this, so here is code ( everything is straightforward -> no explanation is needed 🙂 ):
NSLog(@"Creating image"); CGSize size = CGSizeMake(240.0f, 240.0f); UIGraphicsBeginImageContext(size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetStrokeColorWithColor(context, [[UIColor blackColor] CGColor]); CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]); CGContextFillRect(context, CGRectMake(0.0f, 0.0f, 240.0f, 240.0f)); CGContextSetLineWidth(context, 5.0f); CGContextMoveToPoint(context, 100.0f, 100.0f); CGContextAddLineToPoint(context, 150.0f, 150.0f); CGContextStrokePath(context); UIImage* result = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); imageView.image = result; [imageView setNeedsDisplay]; NSLog(@"Image creation finished");
Example can be found on my GitHub
Best
rob v said:
after almost 2 years someone thanks you for this.
me.
Pingback: Drawing on UIImage Using Core Graphics |
Nadeesha said:
This was very useful & I converted it to Swift
func drawLineOnImage(size: CGSize, image: UIImage, from: CGPoint, to: CGPoint) -> UIImage {
UIGraphicsBeginImageContext(size)
image.drawAtPoint(CGPointZero)
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, 2.0)
CGContextSetStrokeColorWithColor(context, UIColor.blueColor().CGColor)
CGContextMoveToPoint(context, from.x, from.y)
CGContextAddLineToPoint(context, to.x, to.y)
CGContextStrokePath(context)
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resultImage
}