objective-c: draw line on top of UIImage or UIImageView(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 上画线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Objective-c:在 UIImage 或 UIImageView 上画线


基础教程推荐
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01