UIImage Resize Prevention for UIButton

I have a UIButton without text and there are 2 images that I would like to use (one for the normal state and the other for the selected state). Images are smaller than a button.

How to ensure that none of the images scale when drawing a button? Setting imageView properties only scales correctly for the normal state, but not for the selected one.

    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;
+5
source share
1 answer

Assuming you have the height and width of the image, you can 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 do not need to set contentMode / scalefactor.

+10
source

All Articles