Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing UIImage resize for a UIButton

Tags:

iphone

ios5

I have a UIButton with no text and have 2 images I'd like to use (one for normal state and the other for selected state). The images are smaller than the button size.

How do I ensure that neither of the images are scaled when the button is drawn? Setting the imageView properties only change the scale correctly for normal state but not for selected.

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    [button setImage:imageNormal forState:UIControlStateNormal];
    [button setImage:imageSelected forState:UIControlStateSelected];

    // this shows the correct scale in normal mode but not when button is tapped
    button.imageView.contentScaleFactor = 1.0;
    button.imageView.contentMode = UIViewContentModeCenter;
like image 567
Jonas Gardner Avatar asked Jan 02 '12 20:01

Jonas Gardner


1 Answers

Assuming you have the image height and width you could do this:

int topBottom = (button.frame.size.height - imageHeight) / 2;
int leftRight = (button.frame.size.width - imageWidth) / 2;

button.imageEdgeInsets = UIEdgeInsetsMake(topBottom,leftRight,topBottom,leftRight);

And then you don't need to set the contentMode/scalefactor.

like image 148
Philippe Sabourin Avatar answered Sep 19 '22 10:09

Philippe Sabourin