本文介绍了objective-c:在UIImage或UIImageView上绘制线条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在UIImage或UIImageView上绘制一条简单的线?
How do I draw a simple line on top of a UIImage or UIImageView?
推荐答案
以下代码的工作原理是创建一个新图像与原始图像大小相同,将原始图像的副本绘制到新图像上,然后沿新图像的顶部绘制1像素线。
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();
或者,您可以将该行创建为 CAShapeLayer
然后将其作为子视图添加到 UIImageView
(参见)。
Alternatively, you could create the line as a CAShapeLayer
then add it as a subview to the UIImageView
(see this answer).
这篇关于objective-c:在UIImage或UIImageView上绘制线条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!