UIButton圆角时为什么会出现粗糙的黑边? [英] Why is there a rough black edge when rounding corner of UIButton?

查看:35
本文介绍了UIButton圆角时为什么会出现粗糙的黑边?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm adding a UIButton (with background image) to the navigation bar and setting rounded corners with a border. I'm getting a strange black outline on the corners:

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

Here's the code I'm using to create the button from 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];

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

How can I make the border smooth and get rid of the subtle black outline?

推荐答案

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

What you're seeing is your profile image (the person's face) bleeding through the edge. This is because the border is anti-aliased and so has small amounts of transparency through which the profile image can bleed.

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

Since you're clipping the profile image and the border together, there's nothing stopping the profile image from extending through the border. (i.e. clipsToBounds won't clip the content to the inside of the border; it clips everything to the outside of the border) You can prove this by using a bright red image: you'll see a bright red fringe.

如果您可以事先(离线或在代码中)将个人资料图片设为圆形和合适的大小,那么您将避免此问题.

If you can just make the profile image circular and the right size beforehand (either offline or in code) then you'll avoid this problem.

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

The other solutions I see are to either implement your own drawRect: method and do the drawing yourself or to create another sub-layer of the button to hold the image which is clipped in the same way, but without the border. (Either way, you probably need to make your own UIControl for this rather than using UIButton, as manipulating the button's layers could lead to weird behavior.)

这里还有一些其他解决方案:iOS:圆角矩形边框出血颜色

Here are some other solutions, too: iOS: Rounded rectangle with border bleeds color

这篇关于UIButton圆角时为什么会出现粗糙的黑边?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆