gpt4 book ai didi

ios - 为什么 UIButton 的圆角出现粗糙的黑边?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:22:54 24 4
gpt4 key购买 nike

我正在向导航栏添加一个 UIButton(带有背景图像)并设置带边框的圆角。我在角落看到一个奇怪的黑色轮廓:

enter image description here

这是我用来从 viewDidLoad 创建按钮的代码:

ProfileImageService *profileImageService = [ProfileImageService getService];

CGRect frame = CGRectMake(0, 0, 32, 32);
UIButton *button = [[UIButton alloc] initWithFrame:frame];
[button setBackgroundImage:profileImageService.profileImage forState:UIControlStateNormal];
[button addTarget:self action:@selector(showMenu) forControlEvents:UIControlEventTouchUpInside];

button.layer.cornerRadius = button.frame.size.height / 2.0;
button.layer.masksToBounds = YES;
button.clipsToBounds = YES;
button.layer.borderWidth = 3;
button.layer.borderColor = [UIColor colorWithRed:0 green:0.67 blue:0.97 alpha:1].CGColor;

self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

如何使边框平滑并去除细微的黑色轮廓?

最佳答案

您看到的是您的个人资料图片(人脸)从边缘流血。这是因为边框是抗锯齿的,因此具有少量透明度,个人资料图像可以通过该透明度渗出。

由于您将个人资料图片和边框剪裁在一起,因此没有什么能阻止个人资料图片延伸穿过边框。 (即 clipsToBounds 不会将内容裁剪到边框内部;它会将所有内容裁剪到边框外部)您可以使用鲜红色图像证明这一点:您会看到鲜红色的边缘。

如果您可以事先将个人资料图片制作成圆形并设置合适的大小(无论是离线还是在代码中),那么您就可以避免这个问题。

我看到的其他解决方案要么实现您自己的 drawRect: 方法并自己绘制,要么创建按钮的另一个子层来保存以相同方式裁剪但没有边框的图像。 (无论哪种方式,您可能需要为此制作自己的 UIControl 而不是使用 UIButton,因为操纵按钮的层可能会导致奇怪的行为。)

编辑:这里还有一些其他解决方案:iOS: Rounded rectangle with border bleeds color

关于ios - 为什么 UIButton 的圆角出现粗糙的黑边?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24106703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com