一:基本画线:
使用贝赛尔曲线画:
//创建路径
UIBezierPath* aPath = [UIBezierPath bezierPath];
//设置线宽
aPath.lineWidth = 5.0;
//线条拐角
aPath.lineCapStyle = kCGLineCapRound;
//终点处理
aPath.lineJoinStyle = kCGLineCapRound;
//画线的起点
[aPath moveToPoint:CGPointMake(100.0, 0.0)];
//画线的终点
[aPath addLineToPoint:CGPointMake(200.0, 40.0)];
[aPath addLineToPoint:CGPointMake(160, 140)];
[aPath addLineToPoint:CGPointMake(40.0, 140)];
[aPath addLineToPoint:CGPointMake(0.0, 40.0)];
[[UIColor RedColor] set] //设置渲染的颜色
[aPath closePath]; //第五条线通过调用closePath方法得到的
[aPath stroke]; //Draws line 根据坐标点连线渲染
最后一句若为 [aPath fill ];意思是填充渲染
注:
最后渲染的代码要写在drawRect方法中
除了画直线
+ (UIBezierPath *)bezierPathWithRect:(CGRect)rect ; //画矩形
+ (UIBezierPath *)bezierPathWithOvalInRect:(CGRect)rect ; //画圆或者椭圆
+ (UIBezierPath *)bezierPathWithArcCenter:(CGPoint)center radius:(CGFloat)radius startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle clockwise:( BOOL )clockwise; //画弧线
二、画虚线的方法:
第一种:
UIBezierPath* aPath = [BezierPath bezierPath];
aPath.lineWidth = 5.0;
[aPath moveToPoint:CGPointMake(100.0, 0.0)];
[aPath addLineToPoint:CGPointMake(200.0, 40.0)];
[[UIColor RedColor] set] //设置渲染的颜色
CGFloat dashPattern[] = {8,7};// 8实线,7空白
[aPath setLineDash:dashPattern count:1 phase:1];
[aPath stroke]; //Draws line 根据坐标点连线渲染
第二种:
- (void)drawLineWithNumArr:(NSArray *)lengthArr
{
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
[shapeLayer setBounds:self.bounds];
[shapeLayer setPosition:CGPointMake(CGRectGetWidth(self.frame) / 2, CGRectGetHeight(self.frame))];
[shapeLayer setFillColor:[UIColor clearColor].CGColor];
// 设置虚线颜色为blackColor
[shapeLayer setStrokeColor:[UIColor whiteColor].CGColor];
// 设置虚线宽度
[shapeLayer setLineWidth:self.m_LineWidth];
[shapeLayer setLineJoin:kCALineJoinRound];
// 设置线宽,线间距
[shapeLayer setLineDashPattern:lengthArr];
// 设置路径
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0, 0);
CGPathAddLineToPoint(path, NULL,CGRectGetWidth(self.frame), 0);
[shapeLayer setPath:path];
CGPathRelease(path);
// 把绘制好的虚线添加上来
[self.layer addSublayer:shapeLayer];
}
用法:传进来一个数组:
arr = [NSArray arrayWithObjects:[NSNumber numberWithFloat:8], [NSNumber numberWithFloat:3],nil]; 可以传多个,分别为线的长度,空白处的长度,线的长度,空白处的长度............依此类推
arr = [NSArray arrayWithObjects:[NSNumber numberWithFloat:8], [NSNumber numberWithFloat:3], [NSNumber numberWithFloat:5], [NSNumber numberWithFloat:3]nil];
//这样的数组依照线的长度和空白处的长度依次为8,3,5,3........8,3,5,3
第二种相对于第一种可以设置出每小段长度不同的虚线。