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

Arc*_*ian 4 objective-c ios4

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

Cra*_*raz 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();
Run Code Online (Sandbox Code Playgroud)

或者,您可以将该行创建为a CAShapeLayer然后将其添加为子视图UIImageView(请参阅此答案).