实线
//获得上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
//画直线,设置路径颜色
CGContextSetStrokeColorWithColor(ctx, [UIColor grayColor].CGColor);
//设置线宽度
CGContextSetLineWidth(ctx, 2);
//起始点
CGContextMoveToPoint(ctx, 0, height);
//从起始点连线到另一个点
CGContextAddLineToPoint(ctx, width, height);
//画线
CGContextStrokePath(ctx);
虚线
CGContextRef currentContext = UIGraphicsGetCurrentContext();
//设置虚线颜色
CGContextSetStrokeColorWithColor(currentContext, LINE_COLOR.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);
参考:
1. iOS绘制虚线方式总结
2. iOS 使用Quartz 2D画虚线
3. iOS: 使用CGContextRef,CGPath和UIBezierPath来绘画