2

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:

enter image description here

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?

Martin
  • 2,865
  • 4
  • 24
  • 22
  • 2
    make a button with UIButtonTypeCustom (this way you will get a button with no style), then set its frame. try it. – Pawan Rai Jun 08 '14 at 13:44
  • @pawan I tried creating the button using `UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];` and then setting the frame, but I still have exactly the same problem. Any other ideas? – Martin Jun 08 '14 at 14:42

1 Answers1

1

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.

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.

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.)

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

Community
  • 1
  • 1
Jesse Rusak
  • 56,530
  • 12
  • 101
  • 102