如何在不用于UIView的UIImageView上画线? [英] How to draw line on the UIImageView not for UIView?

查看:58
本文介绍了如何在不用于UIView的UIImageView上画线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在UIImageView上画一条线?我正在使用UIImageView子类,它不支持 drawRect:方法.我想在图像视图上画一条线.我怎样才能做到这一点?请帮我.我正在使用下面的代码绘制线条.

How to draw a line on the UIImageView? I am using the UIImageView Sub Class, Its not support drawRect: method. I want to draw a line on the image view. How can I do this? Please help me. I am using below code for draw line.

- (void)drawRect:(CGRect)rect {
    CGContextRef c = UIGraphicsGetCurrentContext();

    CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
    CGContextSetStrokeColor(c, red);
    CGContextBeginPath(c);
    CGContextMoveToPoint(c, 5.0f, 5.0f);
    CGContextAddLineToPoint(c, 50.0f, 50.0f);
    CGContextStrokePath(c);
}

推荐答案

以下代码的工作原理是创建一个与原始图像大小相同的新图像,将原始图像的副本绘制到新图像上,然后绘制一个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();

这篇关于如何在不用于UIView的UIImageView上画线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆