Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objective-c: draw line on top of UIImage or UIImageView

How do I draw a simple line on top of a UIImage or UIImageView?

like image 216
Arcadian Avatar asked Aug 02 '11 00:08

Arcadian


1 Answers

The following code works by creating a new image the same size as the original, drawing a copy of the original image onto the new image, then drawing a 1 pixel line along to the top of the new image.

// UIImage *originalImage = <the image you want to add a line to>
// UIColor *lineColor = <the color of the line>

UIGraphicsBeginImageContext(originalImage.size);

// Pass 1: Draw the original image as the background
[originalImage drawAtPoint:CGPointMake(0,0)];

// Pass 2: Draw the line on top of original image
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 1.0);
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, originalImage.size.width, 0);
CGContextSetStrokeColorWithColor(context, [lineColor CGColor]);
CGContextStrokePath(context);

// Create new image
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

// Tidy up
UIGraphicsEndImageContext();

Alternatively, you could create the line as a CAShapeLayer then add it as a subview to the UIImageView (see this answer).

like image 72
Craz Avatar answered Sep 19 '22 17:09

Craz