Quartz 2D画虚线-b

时间:2022-12-24 15:55:47

这里使用的函数为 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个点

Quartz 2D画虚线-b

(5,5).png

(lengths)2.如果改为lengths{5,10,5} 就表示填充线条和非填充线条交错, 先绘制5个点,跳过5个点,再绘制5个点, 跳过5个点, 绘制10个点

Quartz 2D画虚线-b

(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);

Quartz 2D画虚线-b

phase.png

下图为phase为0,5,8的不同情况 就是第一个的间隔
由于lengths值为{10,5},第一条线就是绘制10,跳过5,反复绘制。
第二条线的phase值为5,则首先绘制【10减去5】,再跳过5,绘制10,反复绘制。
第三条给也如此,先绘制2,再跳过5,如此反复。