objective-c:在UIImage或UIImageView顶部绘制线

objective-c:在UIImage或UIImageView顶部绘制线,objective-c,ios4,Objective C,Ios4,如何在UIImage或UIImageView的顶部绘制一条简单的线?以下代码的工作原理是创建一个与原始图像大小相同的新图像,将原始图像的副本绘制到新图像上,然后沿新图像的顶部绘制一条1像素的线 // UIImage *originalImage = <the image you want to add a line to> // UIColor *lineColor = <the color of the line> UIGraphicsBeginImageContex

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

以下代码的工作原理是创建一个与原始图像大小相同的新图像,将原始图像的副本绘制到新图像上,然后沿新图像的顶部绘制一条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();
//UIImage*原始图像=
//UIColor*线条颜色=
UIGraphicsBeginImageContext(originalImage.size);
//第1步:绘制原始图像作为背景
[原始图像绘制点:CGPointMake(0,0)];
//第二步:在原始图像的顶部画一条线
CGContextRef context=UIGraphicsGetCurrentContext();
CGContextSetLineWidth(上下文,1.0);
CGContextMoveToPoint(上下文,0,0);
CGContextAddLineToPoint(上下文,originalImage.size.width,0);
CGContextSetStrokeColorWithColor(上下文,[lineColor CGColor]);
CGContextStrokePath(上下文);
//创建新图像
UIImage*newImage=UIGraphicsGetImageFromCurrentImageContext();
//收拾
UIGraphicsSendImageContext();
或者,您可以将该行创建为
CAShapeLayer
,然后将其作为子视图添加到
UIImageView
(请参见)。

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

你能更具体地描述你的用例吗?不同的需求会促成不同的完成任务的方式。我想在uiimage或uiimageview上绘制任何符号或对象,就像我们在做签名一样。有办法吗?