I have a couple UIButtons, and in IB they\'re set to Aspect Fit, but for some reason they\'re always stretching. Is there something else you have to set? I tried all the d
You can use imageWithCGImage as shown above (but without the missing parentheses).
Also... millions of non-4.0 phones won't work with that code at all.
btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
This answer is based on @WernerAltewischer's answer.
To avoid having connect my button to an IBOutlet to execute the code on it, I subclassed UIButton's class:
// .h
@interface UIButtonWithImageAspectFit : UIButton
@end
// .m
@implementation UIButtonWithImageAspectFit
- (void) awakeFromNib {
[self.imageView setContentMode:UIViewContentModeScaleAspectFit];
}
@end
Now create a custom button in your xib, and set its image (not the background image):
Then, set its class:
You're done!
Instead of
your button's image aspect fit is now as expected:
I had the same issue, but I couldn't get it to work (perhaps it's a bug with the SDK).
Eventually, as a workaround, I placed a UIImageView
behind my button and set the options I wanted on that, then simply placed a blank UIButton
on top of it.
If you put the image in an UIImageView
behind the button, you'll loose the built-in functionality of the UIButton
class, such as adjustsImageWhenHighlighted
and adjustsImageWhenDisabled
, and of course the ability to set different images for different states (without the hazzle of doing this yourself).
If we want to have an image unstreched for all control states, one approuch is to get the image using imageWithCGImage:scale:orientation
, as in the following method:
- (UIImage *) getScaledImage:(UIImage *)img insideButton:(UIButton *)btn {
// Check which dimension (width or height) to pay respect to and
// calculate the scale factor
CGFloat imgRatio = img.size.width / img.size.height,
btnRatio = btn.frame.size.width / btn.frame.size.height,
scaleFactor = (imgRatio > btnRatio
? img.size.width / btn.frame.size.width
: img.size.height / btn.frame.size.height;
// Create image using scale factor
UIImage *scaledImg = [UIImage imageWithCGImage:[img CGImage]
scale:scaleFactor
orientation:UIImageOrientationUp];
return scaledImg;
}
To implement this we would write:
UIImage *scaledImg = [self getScaledImage:myBtnImg insideButton:myBtn];
[myBtn setImage:scaledImg forState:UIControlStateNormal];
This should prevent the image from stretching in all control states. It worked for me, but let me know if it doesn't!
NOTE: Here we are addressing a problem relating to UIButton
, but the insideButton:
might as well be insideView:
, or whatever one would like to fit the image into.
[button sizeToFit]
worked for me.