drawRect: 小注

drawRect:()默认是什么都不做的,

1.如果基础一个UIView,子类可以使用Core Graphics框架和UIKit在这个方法中完成绘制操作。

2.如果使用其他方法设置子类的content,可以不适用这个方法。

如:你只是改变背景颜色,或者使用他的underlying layer对象(包括直接使用子类的基本层,或者子类添加subview)。

3.如果是直接从一个UIView对象(包括所有系统提供的UIView的子类)继承来的selfVIew,打开这个方法的时候可以不用call super,但是如果你是继承一个自定义的UIView子类,这样myView:selfView,则如果myView需要使用到drawRect:方法的时候需要call super at some point in your implementation。

4.这个方法在第一次displayed view的时候,或者一个事件发生需要改变可见视图的时候被自动调用,你不能够直接调用这个方法,如果需要,可以使用方法setNeedsDisplay或者setNeedsDisplayInRect:替代方法来实现。

5、若使用UIView绘图,只能在drawRect:方法中获取相应的contextRef并绘图。如果在其他方法中获取将获取到一个invalidate的ref并且不能用于画图。drawRect:方法不能手动显示调用,必须通过调用setNeedsDisplay 或者 setNeedsDisplayInRect ,让系统自动调该方法。

6、若使用calayer绘图,只能在drawInContext: 中(类似鱼drawRect)绘制,或者在delegate中的相应方法绘制。同样也是调用setNeedDisplay等间接调用以上方法。

7、若要实时画图,不能使用gestureRecognizer,只能使用touchbegan等方法来掉用setNeedsDisplay实时刷新屏幕

——————————代码:

#import "InfoView.h"

@interface UIView (CanvasImageView)//类别加一个

//多边形

-(void)drawPolygon:(NSArray *)pointArray;

@end

@implementation UIView (CanvasImageView)

-(void)drawPolygon:(NSArray *)pointArray

{

//    NSAssert(pointArray.count>=2,@"数组长度必须大于等于2");

//    NSAssert([[pointArray[0] class] isSubclassOfClass:[NSValue class]], @"数组成员必须是CGPoint组成的NSValue");

    CGContextRef     context = UIGraphicsGetCurrentContext();

    NSValue *startPointValue = pointArray[0];

    CGPoint  startPoint      = [startPointValue CGPointValue];

    CGContextMoveToPoint(context, startPoint.x, startPoint.y);

    for(int i = 1;i<pointArray.count;i++)

    {

//        NSAssert([[pointArray[i] class] isSubclassOfClass:[NSValue class]], @"数组成员必须是CGPoint组成的NSValue");

        NSValue *pointValue = pointArray[i];

        CGPoint  point      = [pointValue CGPointValue];

        CGContextAddLineToPoint(context, point.x,point.y);

    }

    [[UIColor redColor] setFill];

    [[UIColor yellowColor] setStroke];

     CGContextDrawPath(context, kCGPathFillStroke);

}

@end

@implementation InfoView

- (id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        // Initialization code 

    }

    return self;

}

/* Only override drawRect: if you perform custom drawing. An empty implementation adversely affects performance during animation.*/

- (void)drawRect:(CGRect)rect

{

    // Drawing code

    CGPoint uppoint = CGPointMake(rect.size.width/2, rect.size.height/2-15);

    CGPoint downpoint = CGPointMake(rect.size.width/2, rect.size.height/2+15);

    CGPoint arrowpoint = CGPointMake(0, rect.size.height);

    NSArray *pointArr = [NSArray arrayWithObjects:[NSValue valueWithCGPoint:uppoint],[NSValue valueWithCGPoint:downpoint],[NSValue valueWithCGPoint: arrowpoint],[NSValue valueWithCGPoint:uppoint], nil];

    //这一块代码绘图使用的CGContext,只能够再DrawRect:方法中使用,放到别的地方将失效,因为最终调用了这个方法,会将VIew的从新绘制,并将之前的尝试给覆盖了。在别的地方可以进行underlying layer层次的绘图操作~

    [self drawPolygon:pointArr];

}

@end

原文地址:https://www.cnblogs.com/longtaozi/p/3839951.html