一、重寫drawRect方法
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
CGContextRef currentContext = UIGraphicsGetCurrentContext();
//設置虛線顏色
CGContextSetStrokeColorWithColor(currentContext, [UIColor BlackColor].CGColor);
//設置虛線寬度
CGContextSetLineWidth(currentContext, 1);
//設置虛線繪制起點
CGContextMoveToPoint(currentContext, 0, 0);
//設置虛線繪制終點
CGContextAddLineToPoint(currentContext, self.frame.origin.x + self.frame.size.width, 0);
//設置虛線排列的寬度間隔:下面的arr中的數字表示先繪制3個點再繪制1個點
CGFloat arr[] = {3,1};
//下面最后一個參數“2”代表排列的個數。
CGContextSetLineDash(currentContext, 0, arr, 2);
CGContextDrawPath(currentContext, kCGPathStroke);
}
二、采用CAShapeLayer方式繪制虛線
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
[shapeLayer setBounds:self.bounds];
[shapeLayer setPosition:CGPointMake(self.frame.size.width / 2.0, self.frame.size.height)];
[shapeLayer setFillColor:[UIColor clearColor].CGColor];
//設置虛線顏色
shapeLayer setStrokeColor:[UIColor BlackColor].CGColor];
//設置虛線寬度
[shapeLayer setLineWidth:self.frame.size.height];
[shapeLayer setLineJoin:kCALineJoinRound];
//設置虛線的線寬及間距
[shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:3], [NSNumber numberWithInt:1], nil]];
//創建虛線繪制路徑
CGMutablePathRef path = CGPathCreateMutable();
//設置虛線繪制路徑起點
CGPathMoveToPoint(path, NULL, 0, 0);
//設置虛線繪制路徑終點
CGPathAddLineToPoint(path, NULL, self.frame.size.width, 0);
//設置虛線繪制路徑
[shapeLayer setPath:path];
CGPathRelease(path);
//添加虛線
[self.layer addSublayer:shapeLayer];
三、經濟實惠型:采用貼圖的方式繪制虛線(需要設計師切圖配合)
UIImageView *imgDashLineView =[[UIImageView alloc] initWithFrame:CGRectMake(15, 200, self.view.frame.size.width - 30, 1)];
[imgDashLineView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"xuxian.png"]]];
[self.view addSubview:imgDashLineView];