objective-c:在UIImage或UIImageView上绘制线条

时间:2011-08-02 00:12:59

标签: objective-c ios4

如何在UIImage或UIImageView上绘制一条简单的线?

3 个答案:

答案 0 :(得分:14)

以下代码的工作原理是创建与原始图像大小相同的新图像,将原始图像的副本绘制到新图像上,然后在新图像的顶部绘制1像素线。

// 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();

或者,您可以将该行创建为CAShapeLayer,然后将其作为子视图添加到UIImageView(请参阅this answer)。

答案 1 :(得分:0)

对于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()

答案 2 :(得分:0)

对于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
}