Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When UIButton content mode is "center," background image is pixelated

Here's how I'm setting the background image and content mode:

[btn setBackgroundImage:[UIImage imageNamed:@"dots_game_horiz_blue.png"] 
               forState:UIControlStateNormal];
[btn setContentMode:UIViewContentModeCenter];

Is there a reason that the background image would be pixelated? The frame is slightly larger than the image size, and I just want the image to be centered.

like image 525
James Skidmore Avatar asked Aug 05 '09 20:08

James Skidmore


2 Answers

I guess a background image is not considered to be "content" by the UIButton, so the content mode did not apply to the background image. Instead, I set the image of the button and it worked just fine:

[btn setImage:[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dots_game_horiz_blue" ofType:@"png"]] forState:UIControlStateNormal];
[btn setContentMode:UIViewContentModeCenter];
like image 141
James Skidmore Avatar answered Oct 08 '22 03:10

James Skidmore


In your xib / storyboard, in the Attributes inspector, you need to:

  1. Set your UIButton type to Custom
  2. Set your image in the property Image, not Background
  3. Validating step 2, you can see the button frame changed according to the image set. Set the frame as you want it to be, the image will resize itself to fit in
  4. Select Image for the property Edge in order to apply inset to the button image
  5. Enter inset values you need. If you set 5 to Top, Bottom, Left, Right, the image will be centered inside the button, with a border of 5

You can see the changes in the xib / storyboard view, no need to launch a debug.

Tip: Inset is the same for every images of the button (State Config)

like image 44
Rémi Belzanti Avatar answered Oct 08 '22 01:10

Rémi Belzanti