画虚线

绘制一条虚线,此方法可以写到UIImage的分类中,直接写成类方法调用即可。

 1 - (UIImage *)drawDashImageWithFrame:(CGRect)frame andLineColor:(UIColor *)lineColor
 2 {
 3     // 开启图形上下文
 4     UIGraphicsBeginImageContext(frame.size);
 5     
 6     // 获取上下文
 7     CGContextRef cxtRef = UIGraphicsGetCurrentContext();
 8     
 9     // 设置线头样式
10     CGContextSetLineCap(cxtRef, kCGLineCapRound);
11     
12     // 绘制3个点,跳过2个点,绘制3个点,跳过3个点,绘制2个点,如此反复
13     // CGFloat lengths[] = {3,2,3};
14     // 6是每个虚线的长度,5是虚线之间的间隔
15     CGFloat lengths[] = {6,5};
16     
17     // 设置线宽(向两边扩展)
18     CGContextSetLineWidth(cxtRef,1);
19     
20     // 设置线条渲染颜色
21     [lineColor setStroke];
22     
23     // 画虚线
24     // 参数2:第一次绘制的时候跳过多少个点
25     // 参数3:数组
26     // 参数4:数组长度
27     CGContextSetLineDash(cxtRef, 0,lengths, 2);
28     
29     // 开始画线-起点
30     CGContextMoveToPoint(cxtRef, 0.0, 0.0);
31     
32     // 线束画线-终点
33     CGContextAddLineToPoint(cxtRef, [UIScreen mainScreen].bounds.size.width, 0.0);
34     
35     // 设置描边
36     CGContextStrokePath(cxtRef);
37     
38     // 从图形上下文中获取图片
39     UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
40     
41     // 关闭图形上下文
42     UIGraphicsEndImageContext();
43     
44     return img;
45 }
原文地址:https://www.cnblogs.com/panda1024/p/6219137.html