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