前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS_给View加外边框

iOS_给View加外边框

作者头像
mikimo
发布2022-07-20 14:50:51
9290
发布2022-07-20 14:50:51
举报
文章被收录于专栏:iOS开发~iOS开发~

给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];

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

在这里插入图片描述
在这里插入图片描述
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-05-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 给View加外边框
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档