ios 用贝塞尔曲线画虚线,圆角边框

主要是讲画虚线,有个需求给按钮添加虚线的边框 一开始想到layer.border 

// 设置边线

self.layer.borderWidth = 1;

self.layer.borderColor = [UIColor orangeColor].CGColor;

// 添加四个角的弧度

self.layer.cornerRadius = 5;

self.layer.masksToBounds = YES;


但是发现这个方法没办法画虚线

ios 用贝塞尔曲线画虚线,圆角边框_第1张图片



下面的的办法

- (void)drawRect:(CGRect)rect {

// 线的宽度

CGFloat lineWidth = 1.4;

// 根据线的宽度 设置画线的位置

CGRect rect1 =  CGRectMake(lineWidth * 0.5, lineWidth * 0.5, rect.size.width - lineWidth , rect.size.height - lineWidth);

// 获取图像上下文

CGContextRef context = UIGraphicsGetCurrentContext();

// 设置线的宽度

CGContextSetLineWidth(context, lineWidth);

// 设置线的颜色

CGContextSetStrokeColorWithColor(context, [UIColor orangeColor].CGColor);

// 设置虚线和实线的长度

CGFloat lengths[] = { 2.5, 1.5 };

CGContextSetLineDash(context, 0, lengths,1);

// CGContextSetLineDash(context, 0, lengths, 1);

// 画矩形path 圆角5度

UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:rect1 cornerRadius:5];

// 添加到图形上下文

CGContextAddPath(context, bezierPath.CGPath);

// 渲染

CGContextStrokePath(context);

}

效果如下

ios 用贝塞尔曲线画虚线,圆角边框_第2张图片
// ****  画虚线

CGSize size = rect.size;

//    CGContextRef context = UIGraphicsGetCurrentContext();

CGContextBeginPath(context);

CGContextSetLineWidth(context, 1.5);

CGContextSetStrokeColorWithColor(context, [UIColor orangeColor].CGColor);

CGFloat lengths1[] = { 3, 1.5 };

CGContextSetLineDash(context, 0, lengths1, 1);

CGContextMoveToPoint(context, 12.0, 12.0);

CGContextAddLineToPoint(context, size.width - 12, 12.0);

CGContextStrokePath(context);

ios 用贝塞尔曲线画虚线,圆角边框_第3张图片

你可能感兴趣的:(ios 用贝塞尔曲线画虚线,圆角边框)