ios UIImageView 部分圆角(加上 borderWidth、borderColor 效果修复)

本文介绍如何在iOS开发中使用UIImageView实现精确的圆角和边框效果,避免交付时因视觉效果不佳而遇到的问题。通过调整CAShapeLayer的使用方式,确保UIImageView在设置特定圆角和边框宽度时,能呈现高质量的视觉效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

关于 UIImageView 部分圆角 先扔代码吧,具体的我这里就不讲了。(本文重点不在这里)

/**
 *  设置部分圆角(绝对布局)
 *
 *  @param corners 需要设置为圆角的角 UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomLeft | UIRectCornerBottomRight | UIRectCornerAllCorners
 *  @param radii   需要设置的圆角大小 例如 CGSizeMake(20.0f, 20.0f)
 */
- (void)addRoundedCorners:(UIRectCorner)corners withRadii:(CGSize)radii {
    CAShapeLayer* shape = [CAShapeLayer layer];
    shape.path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:radii].CGPath;
    self.layer.mask = shape;
}

但是问题来了如果我们加上 borderWidth、borderColor会是什么样子呢?(代码、效果图如下)

   UIImageView *imageView = [[UIImageView alloc] init];
    imageView.layer.borderColor = [UIColor redColor].CGColor;
    imageView.layer.borderWidth = 2;
    imageView.frame = CGRectMake(100, 200, 80, 80);
    [self.view addSubview:imageView];
    [imageView addRoundedCorners:UIRectCornerTopLeft | UIRectCornerTopRight withRadii:CGSizeMake(20, 20)];
   

在这里插入图片描述
可以看到效果图边框效果真的差,如果交付会被打死的。
那怎么处理呢,先上代码吧。

   UIImageView *imageView = [[UIImageView alloc] init];
    imageView.frame = CGRectMake(100, 200, 80, 80);
    [self.view addSubview:imageView];
    [imageView addRoundedCorners:UIRectCornerTopLeft | UIRectCornerTopRight withRadii:CGSizeMake(20, 20)];
   
    CAShapeLayer* shape = [CAShapeLayer layer];
    shape.path = ((CAShapeLayer *)imageView.layer.mask).path;//path 取- (void)addRoundedCorners:(UIRectCorner)corners withRadii:(CGSize)radii 函数中的 path
    shape.strokeColor = [UIColor redColor].CGColor;//边框色
    shape.lineWidth = 2*2;//2*边框宽度
    shape.fillColor = [UIColor clearColor].CGColor;//填充色
    [imageView.layer addSublayer:shape];//addSublayer
    [imageView sd_setImageWithURL:[NSURL URLWithString:@"https://images2.bestjlb.com/jlboss7370d8b2315203cfd4fdff617fd6013215427879667496070.jpg"]];

效果图
在这里插入图片描述
这个效果应该可以交付了吧,如果有什么疑问大家考虑下图层应该就明白了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值