使用CGContext 绘图方法
1.重写draw rect 方法:
-(void)drawRect:(CGRect)rect{
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextSetLineWidth(context,2.0f);//线宽度这里是像素大小
CGContextSetStrokeColorWithColor(context,[UIColor blueColor].CGColor);
CGFloat lengths[] = {1,3};//先画2个点再画2个点
CGContextSetLineDash(context,0, lengths,2);//注意2(count)的值等于lengths数组的长度
CGContextMoveToPoint(context,0,0);
CGContextAddLineToPoint(context,self.frame.size.width / 2.0f,0);
CGContextStrokePath(context);
CGContextClosePath(context);
}
iOS 画虚线方法总结 作者有提到另外一种方法叫通过UIImage的绘图方法来绘制 的这种方法,其实还是通过CGContext 的方式绘制曲线。
具体CGContext 相关的内容可见:
apple 官网
例子请见
通过CAShapeLayer方式绘制虚线
2.通过CAShapeLayer方式绘制虚线
/**
** lineView: 需要绘制成虚线的view
** lineLength: 虚线的宽度
** lineSpacing: 虚线的间距
** lineColor: 虚线的颜色
**/
- (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor
{
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
[shapeLayer setBounds:lineView.bounds];
[shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];
[shapeLayer setFillColor:[UIColor clearColor].CGColor];
// 设置虚线颜色为blackColor
[shapeLayer setStrokeColor:lineColor.CGColor];
// 设置虚线宽度
[shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];
[shapeLayer setLineJoin:kCALineJoinRound];
// 设置线宽,线间距
[shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];
// 设置路径
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0, 0);
CGPathAddLineToPoint(path, NULL,CGRectGetWidth(lineView.frame), 0);
[shapeLayer setPath:path];
CGPathRelease(path);
// 把绘制好的虚线添加上来
[lineView.layer addSublayer:shapeLayer];
}