添加 虚线边框|单边框

2019-08-06  本文已影响0人  罂粟之城

在iOS中某些控件是具备直接使用 layer.boder 属性设置边框的宽度和颜色即可添加实现边框;并且可以实现圆角边框。

但是虚线边框的实现,只有依靠iOS具备的绘制功能实现。

具体实现代码如下:

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];
可使用添加一个layer去添加到对应边框位置去:

CALyaer *borderLayer = [CALayer layer];
borderLayer.backgroundColor = [UIColor redColor];
[testUI.layer addSublayer:borderLayer];
上一篇下一篇

猜你喜欢

热点阅读