iOS_给View加外边框

2022-07-20 14:50:51 浏览数 (1)

给View加外边框

需求是:需要给头像加边框

UIImageView显示头像:

代码语言:javascript复制
UIImageView *imgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mo_avatar"]];
imgV.contentMode = UIViewContentModeScaleAspectFill;
imgV.frame = CGRectMake(50, 210, 100, 100);
imgV.layer.masksToBounds = YES;
imgV.layer.cornerRadius = 8.0;
[self.view addSubview:imgV];

边框正常会直接这么设置:

代码语言:javascript复制
imgV.layer.borderWidth = borderWidth;
imgV.layer.borderColor = [UIColor cyanColor].CGColor;

这么写其实加的是内边框,就算扩大imgVframe,也还是会有部分图片被边框遮住。

解决方案: 另创建一个CALayer实现:

代码语言:javascript复制
CALayer *layer = [CALayer layer];
layer.frame = CGRectMake(imgV.frame.origin.x - borderWidth,
                         imgV.frame.origin.y - borderWidth,
                         imgV.frame.size.width   2 * borderWidth,
                         imgV.frame.size.height   2 * borderWidth);
layer.masksToBounds = YES;
layer.cornerRadius = imgV.layer.cornerRadius   borderWidth;
layer.borderWidth = borderWidth;
layer.borderColor = [UIColor cyanColor].CGColor;
[self.view.layer addSublayer:layer];

一下是效果对比图: 上:加的内边距 下:加的外边距

0 人点赞