drawRect是UIView的一个方法,用于View的绘制操作。先贴上一段代码:


CustomView.m

- (void)drawRect:(CGRect)rect{
    CGContextRef context=UIGraphicsGetCurrentContext();
    
    CGContextSetLineWidth(context, 2);
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
    
    CGContextMoveToPoint(context, 0, 0);
    CGContextAddLineToPoint(context, rect.size.width, 0);
    CGContextAddLineToPoint(context, rect.size.width, rect.size.height);
    CGContextAddLineToPoint(context, 0, rect.size.height);
    CGContextAddLineToPoint(context, 0, 0);
    
    CGContextStrokePath(context);
    
}

1、CustomView继承自UIView,并重写drawRect方法进行自定义绘制。

2、在drawRect方法里,绘制的主要流程如下:

(1)获得绘制上下文

    CGContextRef context=UIGraphicsGetCurrentContext();

(2)设置线条(画笔)属性。这里只设置了线条颜色和粗细。

    CGContextSetLineWidth(context, 2);
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);

(3)设置绘制的路线。

    CGContextMoveToPoint(context, 0, 0);
    CGContextAddLineToPoint(context, rect.size.width, 0);
    CGContextAddLineToPoint(context, rect.size.width, rect.size.height);
    CGContextAddLineToPoint(context, 0, rect.size.height);
    CGContextAddLineToPoint(context, 0, 0);

(4)绘制。

CGContextStrokePath(context);

3、drawRect方法一般只会执行一次,如果要多次重绘,需要调用setNeedsDisplay或setNeedsDisplayInRect,如:

    CustomView *cView=[[CustomView alloc] initWithFrame:CGRectMake(100, 200, 200, 200)];
    cView.backgroundColor=[UIColor redColor];
    [bgView addSubview:cView];
    [cView performSelector:@selector(setNeedsDisplay) withObject:nil afterDelay:5.0f];//5s后重绘

4、如果一开始初始化CustomView时未设置frame,则drawRect不会被调用。

5、绘图上下文(CGContextRef)只有在drawRect才有效,即以下代码只有在drawRect中才会获得正确的context,其他地方及时调用了也不回有结果。

CGContextRef context=UIGraphicsGetCurrentContext();

6、绘图上下文就是指当前的CustomView,可以把CustomView想象成一个画布,drawRect方法就是在这块画布上作图。