iOS view添加虚线边框

时间:2021-7-9 作者:qvyue

有时候需要为UIView添加虚线描边,本文记录一种实现方式,主要是通过对UIView的根layer添加CAShapeLayer来完成。效果图如下:

UIView虚线边框示意图

iOS view添加虚线边框

WeChat_1496803481.jpeg

核心代码示例如下:

CGSize screenSize = [UIScreen mainScreen].bounds.size;

CGFloat viewWidth = 200;

CGFloat viewHeight = 200;

UIView *view = [[UIView alloc] initWithFrame:CGRectMake((screenSize.width – viewWidth)/2, (screenSize.height – viewHeight) / 2, viewWidth, viewHeight)];

view.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];

view.layer.cornerRadius = CGRectGetWidth(view.bounds)/2;

CAShapeLayer *borderLayer = [CAShapeLayer layer];

borderLayer.bounds = CGRectMake(0, 0, viewWidth, viewHeight);

borderLayer.position = CGPointMake(CGRectGetMidX(view.bounds), CGRectGetMidY(view.bounds));

//矩形

//    borderLayer.path = [UIBezierPath bezierPathWithRect:borderLayer.bounds].CGPath;

//圆形,圆角

borderLayer.path = [UIBezierPath bezierPathWithRoundedRect:borderLayer.bounds cornerRadius:CGRectGetWidth(borderLayer.bounds)/2].CGPath;

borderLayer.lineWidth = 1. / [[UIScreen mainScreen] scale];

//虚线边框

borderLayer.lineDashPattern = @[@8, @8];

//实线边框

//    borderLayer.lineDashPattern = nil;

borderLayer.fillColor = [UIColor clearColor].CGColor;

borderLayer.strokeColor = [UIColor redColor].CGColor;

[view.layer addSublayer:borderLayer];

[self.view addSubview:view];

//可通过修改UIBezierPath来改变虚线框的路径。如果想把边框绘制成实线,可将borderLayer.lineDashPattern置为nil即可。

转载,如有侵权联系立删

转自:武一顶顶

链接:https://www.jianshu.com/p/e6b0f6213bb9

声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:qvyue@qq.com 进行举报,并提供相关证据,工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。