6

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

Arcadian
  • 4,312
  • 12
  • 64
  • 107
  • Can you be more specific on your use case? Different needs would precipitate different ways of accomplishing your task. – Wayne Hartman Aug 02 '11 at 01:01

3 Answers3

15

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).

Community
  • 1
  • 1
Craz
  • 8,193
  • 2
  • 23
  • 16
  • I want to draw any symbols or any objects on uiimage or uiimageview, just like we are doing signature. Is there any way ? – Abha Jun 24 '16 at 08:13
-1

For Swift 3.0

    UIGraphicsBeginImageContext(originalImage.size)
    originalImage.draw(at: CGPoint(x: 0, y: 0))
    let context = UIGraphicsGetCurrentContext()!
    context.setLineWidth(2)
    context.move(to: CGPoint(x: 0, y: originalImage.size.height - 2))
    context.addLine(to: CGPoint(x: originalImage.size.width, y: originalImage.size.height - 2))
    context.setStrokeColor(UIColor.red.cgColor)
    context.strokePath()
    let finalImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
Niklas
  • 1,322
  • 14
  • 11
-1

For Swift 2.3

func drawLineOnImage(size: CGSize, image: UIImage, from: CGPoint, to: CGPoint) -> UIImage {
    UIGraphicsBeginImageContext(size)
    image.drawAtPoint(CGPointZero)
    let context     = UIGraphicsGetCurrentContext()
    CGContextSetLineWidth(context, 1.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
}
Nadeesha Lakmal
  • 433
  • 5
  • 9