畫虛線需要用到函數:
CGContextSetLineDash
此函數需要四個參數:
- context – 這個不用多說
- phase - 稍后再說
- lengths – 指明虛線是如何交替繪制,具體看例子
- count – lengths數組的長度
CGContextRef context =UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context, [UIColorwhiteColor].CGColor);
float lengths[] = {10,10};
CGContextSetLineDash(context, 0, lengths,2);
CGContextMoveToPoint(context, 10.0, 20.0);
CGContextAddLineToPoint(context, 310.0,20.0);
CGContextStrokePath(context);
CGContextClosePath(context);
lengths的值{10,10}表示先繪制10個點,再跳過10個點,如此反復,如圖:
0_1328429173RRMR.png
如果把lengths值改為{10, 20, 10},則表示先繪制10個點,跳過20個點,繪制10個點,跳過10個點,再繪制20個點,如此反復,如圖:
0_1328429523yqLp.png
注意count的值等于lengths數組的長度
float lengths[] = {10,5};
CGContextSetLineDash(context, 0, lengths, 2);
CGContextMoveToPoint(context, 0.0, 20.0);
CGContextAddLineToPoint(context, 310.0, 20.0);
CGContextStrokePath(context);
CGContextSetLineDash(context, 5, lengths, 2);
CGContextMoveToPoint(context, 0.0, 40.0);
CGContextAddLineToPoint(context, 310.0, 40.0);
CGContextStrokePath(context);
CGContextSetLineDash(context, 8, lengths, 2);
CGContextMoveToPoint(context, 0.0, 60.0);
CGContextAddLineToPoint(context, 310.0, 60.);
CGContextStrokePath(context);
0_13284305046O6f.png
由于lengths值為{10,5},第一條線就是繪制10,跳過5,反復繪制。
第二條線的phase值為5,則首先繪制【10減去5】,再跳過5,繪制10,反復繪制。
第三條給也如此,先繪制2,再跳過5,如此反復。
項目擴展 ---畫彎曲的虛線
-(void)drawRect:(CGRect)rect
{
CGFloat selfW = rect.size.width;
CGFloat selfH = rect.size.height;
CGPoint point1 = CGPointMake(selfW, 5);
CGPoint point2 = CGPointMake(10, 5);
CGPoint point3 = CGPointMake(5, 10);
CGPoint point4 = CGPointMake(5, selfH-10);
CGPoint point5 = CGPointMake(10, selfH-5);
CGPoint point6 = CGPointMake(selfW, selfH-5);
//貝斯曲線的控制點 --畫圓角用
CGPoint controlPoint1 = CGPointMake(5, 5);
CGPoint controlPoint2 = CGPointMake(5, selfH-5);
CGContextRef context =UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextSetLineWidth(context, 1);
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
const CGFloat lengths[] = {2,2};
CGContextSetLineDash(context, 0, lengths,2);
CGContextSetLineJoin(context, kCGLineJoinRound);
CGContextMoveToPoint(context, point1.x, point1.y);
CGContextAddLineToPoint(context, point2.x, point2.y);
CGContextAddQuadCurveToPoint(context, controlPoint1.x ,controlPoint1.y , point3.x,point3.y );
CGContextAddLineToPoint(context, point4.x, point4.y);
CGContextAddQuadCurveToPoint(context,controlPoint2.x , controlPoint2.y , point5.x ,point5.y);
CGContextAddLineToPoint(context, point6.x, point6.y);
CGContextStrokePath(context);
CGContextClosePath(context);
}
效果圖:
效果圖