這里使用的函數為 CGContextSetLineDash,有四個參數 CGContextSetLineDash(<#CGContextRef _Nullable c#>, <#CGFloat phase#>, <#const CGFloat * _Nullable lengths#>, <#size_t count#>)
context – 這個不用多說
phase - 稍后再說
lengths – 指明虛線是如何交替繪制,具體看例子
count – lengths數組的長度
CGContextAddPath(ctx, rectPath.CGPath);
CGContextSetStrokeColorWithColor(ctx, [UIColor blackColor].CGColor);
CGContextSetLineWidth(ctx, 1.0);
CGFloat lengths[] = {5, 5};
CGContextSetLineDash(ctx, 0.0, lengths, 2); //1
CGContextStrokePath(ctx);
(lengths)1.這里的lengths{5,5} 表示繪制5個點,跳過5個點
(5,5).png
(lengths)2.如果改為lengths{5,10,5} 就表示填充線條和非填充線條交錯, 先繪制5個點,跳過5個點,再繪制5個點, 跳過5個點, 繪制10個點
(5,,10,5).png
然后count很簡單,就是lengths的數組長度.
phase 這里指的是開始跳過的距離
CGFloat 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);
phase.png
下圖為phase為0,5,8的不同情況 就是第一個的間隔
由于lengths值為{10胰锌,5},第一條線就是繪制10酬土,跳過5格带,反復繪制刹枉。
第二條線的phase值為5屈呕,則首先繪制【10減去5】,再跳過5蟋软,繪制10嗽桩,反復繪制。
第三條給也如此碌冶,先繪制2,再跳過5扑庞,如此反復嫩挤。