开发项目过程中UI设计会有些虚线边框的设计,这种情况下一般使用图片;
下面我给大家写个用代码实现虚线的,省的使用图片了。
直接上代码
self.view.backgroundColor = UIColor.whiteColor;
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(80, 300, 260, 200)];
[self.view addSubview:myView];
myView.backgroundColor = UIColor.whiteColor;
// 设置圆角的半径
CGFloat cornerRadius = 10.0;
// 设置虚框的颜色
UIColor *borderColor = [UIColor blackColor];
// 设置虚框的宽度
CGFloat borderWidth = 1.0;
// 创建圆角效果
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.path = [UIBezierPath bezierPathWithRoundedRect:myView.bounds cornerRadius:cornerRadius].CGPath;
myView.layer.mask = maskLayer;
// 创建虚线样式
CAShapeLayer *borderLayer = [CAShapeLayer layer];
borderLayer.strokeColor = borderColor.CGColor;
borderLayer.fillColor = nil;
borderLayer.lineWidth = borderWidth;
borderLayer.lineJoin = kCALineJoinRound;
borderLayer.lineDashPattern = @[@4, @2]; // 设置虚线的长度和间距,可以根据需要调整
// 创建虚线路径,使用CGRectInset来缩小虚线框,使其不超过视图边界
UIBezierPath *borderPath = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(myView.bounds, borderWidth / 2, borderWidth / 2) cornerRadius:cornerRadius];
borderLayer.path = borderPath.CGPath;
// 将虚线图层添加到视图图层上
[myView.layer addSublayer:borderLayer];