需求:
需要实现虚线功能
实现方法:
方法一:
使用贝塞尔曲线实现
- (void)addBorderToLayer:(UIView *)view
{
CAShapeLayer *border = [CAShapeLayer layer];
// 线条颜色
border.strokeColor = [UIColor lightGrayColor].CGColor;
border.fillColor = nil;
UIBezierPath *pat = [UIBezierPath bezierPath];
[pat moveToPoint:CGPointMake(0, 0)];
if (CGRectGetWidth(view.frame) > CGRectGetHeight(view.frame)) {
[pat addLineToPoint:CGPointMake(view.bounds.size.width, 0)];
}else{
[pat addLineToPoint:CGPointMake(0, view.bounds.size.height)];
}
border.path = pat.CGPath;
border.frame = view.bounds;
// 不要设太大 不然看不出效果
border.lineWidth = 0.5;
border.lineCap = @"butt";
// 第一个是 线条长度 第二个是间距 nil时为实线
border.lineDashPattern = @[@6, @10];
[view.layer addSublayer:border];
}
方法二:
Quartz 2D绘制
- (void)addBorderToLayer2:(UIView *)view
{
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
[shapeLayer setBounds:view.bounds];
[shapeLayer setPosition:CGPointMake(CGRectGetWidth(view.frame) / 2, CGRectGetHeight(view.frame)/2)];
[shapeLayer setStrokeColor:[UIColor lightGrayColor].CGColor];
[shapeLayer setLineWidth:0.5];
// 设置线宽,线间距
[shapeLayer setLineDashPattern:@[@6,@10]];
// 设置路径
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0, 0);
if (CGRectGetWidth(view.frame) > CGRectGetHeight(view.frame)) {
CGPathAddLineToPoint(path, NULL, CGRectGetWidth(view.frame),0);
}else{
CGPathAddLineToPoint(path, NULL, 0,CGRectGetHeight(view.frame));
}
[shapeLayer setPath:path];
CGPathRelease(path);
// 把绘制好的虚线添加上来
[view.layer addSublayer:shapeLayer];
}