iOS 画虚线以及drawRect的使用总结:

#import <UIKit/UIKit.h>

@interface DashesLineView : UIView

@property(nonatomic)CGPoint startPoint;//虚线起点
@property(nonatomic)CGPoint endPoint;//虚线终点
@property(nonatomic,strong)UIColor *lineColor;//虚线颜色

@end

#import "DashesLineView.h"

@implementation DashesLineView

- (id)initWithFrame:(CGRect)frame
{
self= [super initWithFrame:frame];
if(self) {
// Initialization code
}

return self;
}

- (void)drawRect:(CGRect)rect
{
CGContextRef context =UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextSetLineWidth(context,0.5);//线宽度
CGContextSetStrokeColorWithColor(context,self.lineColor.CGColor);
CGFloat lengths[] = {4,2};//先画4个点再画2个点
CGContextSetLineDash(context,0, lengths,2);//注意2(count)的值等于lengths数组的长度
CGContextMoveToPoint(context,self.startPoint.x,self.startPoint.y);
CGContextAddLineToPoint(context,self.endPoint.x,self.endPoint.y);
CGContextStrokePath(context);
CGContextClosePath(context);
}

@end

drawRect在以下情况下会被调用:

1、如果在UIView初始化时没有设置rect大小,将直接导致drawRect不被自动调用。drawRect 掉用是在Controller->loadView, Controller->viewDidLoad 两方法之后掉用的.所以不用担心在 控制器中,这些View的drawRect就开始画了.这样可以在控制器中设置一些值给View(如果这些View draw的时候需要用到某些变量 值).
2、该方法在调用sizeToFit后被调用,所以可以先调用sizeToFit计算出size。然后系统自动调用drawRect:方法。
3、通过设置contentMode属性值为UIViewContentModeRedraw。那么将在每次设置或更改frame的时候自动调用drawRect:。
4、直接调用setNeedsDisplay,或者setNeedsDisplayInRect:触发drawRect:,但是有个前提条件是rect不能为0。
以上1,2推荐;而3,4不提倡

drawRect方法使用注意点:

1、 若使用UIView绘图,只能在drawRect:方法中获取相应的contextRef并绘图。如果在其他方法中获取将获取到一个invalidate 的ref并且不能用于画图。drawRect:方法不能手动显示调用,必须通过调用setNeedsDisplay 或 者 setNeedsDisplayInRect,让系统自动调该方法。
2、若使用calayer绘图,只能在drawInContext: 中(类似鱼drawRect)绘制,或者在delegate中的相应方法绘制。同样也是调用setNeedDisplay等间接调用以上方法
3、若要实时画图,不能使用gestureRecognizer,只能使用touchbegan等方法来掉用setNeedsDisplay实时刷新屏幕

原文地址:https://www.cnblogs.com/xilanglang/p/5073233.html