给View加外边框
需求是:需要给头像加边框
UIImageView
显示头像:
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;
这么写其实加的是内边框,就算扩大imgV
的frame
,也还是会有部分图片被边框遮住。
解决方案:
另创建一个CALayer
实现:
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];
一下是效果对比图: 上:加的内边距 下:加的外边距