利用drawRect画线的简单用法

关于动画的一些简单应用。这里以画直线为例。

绘图的方法都是在UIView的drawRect中
执行的,对于一次性就能画好的图,直接使用drawRect即可,无需调用UIView的setNeedsDisplay。
但若想多次调用drawRect,即想做出动画效果(如柱状图,效果是慢慢升起),术语叫重绘,那么就需要调用UIView的setNeedsDisplay方法。使用了setNeedsDisplay方法,程序会调用drawRect。类似于cellForRowAtIndexPath,无需在initWithFrame或viewDidLoad中调用,便可以直接被系统执行。

下面画一条不规则的折线,没有使用setNeedsDisplay。必要代码

 1 -(void)drawRect:(CGRect)rect{ 
 2     self.backgroundColor = [UIColor lightGrayColor];
 3     //获得处理的上下文
 4     CGContextRef context = UIGraphicsGetCurrentContext();
 5     //设置线的颜色
 6     CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
 7     //起始点设置为(0,0):注意这是上下文对应区域中的相对坐标,
 8     CGContextMoveToPoint(context, 0, 0);
 9     //设置下一个坐标点
10     CGContextAddLineToPoint(context, 100, 100);
11     //设置下一个坐标点
12     CGContextAddLineToPoint(context, 0, 150);
13     //设置下一个坐标点
14     CGContextAddLineToPoint(context, 50, 180);
15     //设置下一个坐标点
16     CGContextAddLineToPoint(context, 10, 18);
17     //连接上面定义的坐标点,也就是开始绘图
18     CGContextStrokePath(context);
19 }

以下代码是非必要的。关于线条的颜色设置也可以认为不必要

//设置线条样式
CGContextSetLineCap(context, kCGLineCapSquare);
//设置线条粗细宽度,默认为1.0
CGContextSetLineWidth(context, 1.0);
//开始一个起始路径
CGContextBeginPath(context);

效果如下

若想画成柱状图,则只需用CGContextSetLineWidth把线画粗点就可以了,要是折线图也同理。

 

**********************    2015-09-16 补充    **********************    

CADisplayLink是一个能将特定内容周期性绘制到屏幕上的定时器类,与NSTimer类似,但精确度比NSTimer高,适合做界面的不停重绘。需要注意下frameInterval的用法,表示每隔多少帧运行@selector的方法。用法如下:

_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(toDoDrawLine)];
//frameInterval表示间隔多少帧运行一次@selector方法,默认是1,即每帧都调用一次
_displayLink.frameInterval = 3;

setNeedsDisplay为UIView的方法,当需要刷新view时,可调用该方法,setNeedsDisplay则会自动调用drawRect方法。
在drawRect方法中,需要获取当前上下文,UIGraphicsGetCurrentContext一般情况下只用在drawRect方法中。context相当于画布,可以在这上边绘制图形。

-(void)drawRect:(CGRect)rect{
    //获取当前上下文,UIGraphicsGetCurrentContext只能在drawRect里使用
    //context相当于画布,可以在这上边绘制图形
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    [self drawBarWith:context];
}

绘制一些文本内容时,需要用drawInRect:withAttributes方法来设置文本的属性。用法类似如下:

//文字属性
UIFont *labelFont = [UIFont systemFontOfSize:15];
UIColor *labelColor = [UIColor blackColor];
//label文字的背景颜色。可设置为其它颜色
UIColor *labelBackColor = [UIColor clearColor];
//文字的段落样式
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.alignment = NSTextAlignmentCenter;
NSDictionary *dict = @{NSFontAttributeName:labelFont,NSForegroundColorAttributeName:labelColor,NSParagraphStyleAttributeName:style,NSBackgroundColorAttributeName:labelBackColor};
[@"标题A" drawInRect:CGRectMake(dataX, ViewHeight-15, _barPadding+_barWidth, 15) withAttributes:dict];
原文地址:https://www.cnblogs.com/Apologize/p/4276772.html