UIButton won't go to Aspect Fit in iPhone
Asked Answered
P

21

113

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 different view modes and none of them work, they all stretch.

Privation answered 11/8, 2010 at 16:40 Comment(2)
@Werner Altesischer's answer is the right one. Make the appropriate changes.Deceased
@Privation Are you setting background image or image? background image does not support it, only image.Cinquefoil
M
46

I've had that problem before. I solved it by putting my image in a UIImageView, where contentMode settings actually work, and putting a transparent custom UIButton over top of that.

EDIT: This answer is obsolete. See @Werner Altewischer's answer for the correct answer in modern versions of iOS.

Minton answered 11/8, 2010 at 17:2 Comment(3)
Yeah tried that, but now can't get the button to refit to the imagePrivation
How do you manage button states with this technique? Seems like responding to user interaction like "highlighted" would be a nightmare.Hentrich
This might have been the right way to do this 2.5 years ago when this question was answered, but now you can edit the UIButton's internal ImageView and set the the content mode there. See the answer by @Werner AltewischerTeletypewriter
R
243

The solution is to set the contentMode on the imageView property of the UIButton. The UIButton has to be created with custom type for this to work I believe (otherwise nil is returned for this property).

Rehm answered 22/10, 2010 at 10:10 Comment(10)
This worked for me: [button.imageView setContentMode:UIViewContentModeScaleAspectFit];Paschall
This works for me also but if I set adjustsImageWhenHighlighted=YES, the image is stretched again when I tap on the button.Charismatic
Set adjustImageWhenHighlighted to NO and supply an image yourself for the highlighted state insteadRehm
The stretching in adjustsImage has been eliminated in iOS 6.Cordovan
In iOS 8, this actually doesn't work for me. The original answer (with placing an imageView behind a transparent button) works best.Pigeontoed
in SWIFT: button.imageView.contentMode = UIViewContentMode.ScaleAspectFitBoucher
in Swift du jour: button.imageView!.contentMode = UIViewContentMode.scaleAspectFitPlasticine
Is this possible within the storyboard designer, or must it be set in code?Guanase
Also, on iOS 11+, the content mode has to be set before the image. Otherwise it will only get its good shape after taping on it.Adelia
What might cause an image set as the image for a button to appear cut off? Text appears fine if put instead of imageOverstreet
C
63

This method worked for me very well.:

In Xib select the button and set user defined runtime attributes:

  • Key path: self.imageView.contentMode
  • Type: Number
  • Value: 1

Click here to see more clearly the solution

We use number because you cant use enum there. But the UIViewContentModeScaleAspectFit is equal to 1.

Catcall answered 8/3, 2016 at 9:35 Comment(4)
This also updated the image in the interface builder during design time. Great solution.Haem
Great solution, few code and works like a charm , the enum is based on content mode list items.Nagual
You can also add an extension to make it a bit easier: extension UIButton { @IBInspectable var imageContentMode: Int { get {return imageView?.contentMode.rawValue ?? 0} set {imageView?.contentMode = UIViewContentMode(rawValue: newValue) ?? .scaleAspectFit} } }Jihad
Without 'self' imageView.contentMode worked for me!Cuthbertson
M
46

I've had that problem before. I solved it by putting my image in a UIImageView, where contentMode settings actually work, and putting a transparent custom UIButton over top of that.

EDIT: This answer is obsolete. See @Werner Altewischer's answer for the correct answer in modern versions of iOS.

Minton answered 11/8, 2010 at 17:2 Comment(3)
Yeah tried that, but now can't get the button to refit to the imagePrivation
How do you manage button states with this technique? Seems like responding to user interaction like "highlighted" would be a nightmare.Hentrich
This might have been the right way to do this 2.5 years ago when this question was answered, but now you can edit the UIButton's internal ImageView and set the the content mode there. See the answer by @Werner AltewischerTeletypewriter
T
24

If you are doing this in Interface Builder, you can use the Runtime attributes inspector to set this directly without any code.

Set your Key Path on the button to be "imageView.contentMode" with a type of "Number" and a value of "1" (or whichever mode you would like).

imageview.contentMode = 1

Tetrabrach answered 10/2, 2017 at 22:42 Comment(0)
N
17

Use button's imageView for contentMode. Not directly on the button itself.

homeButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
homeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
homeButton.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
[homeButton setImage:[UIImage imageNamed:kPNGLogo] forState:UIControlStateNormal];
Northnortheast answered 11/9, 2016 at 20:30 Comment(0)
P
6

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.

Purposeless answered 14/12, 2010 at 13:17 Comment(0)
B
6

I had this problem a while back. The issue I had was i was trying to apply this effect to the background UIButton which is limited and therefore means you cannot adjust it as easy.

The trick is to set it as just an image then apply @ayreguitar's technique and that should fix it!

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setContentMode:UIViewContentModeScaleAspectFill];
[myButton setImage:@"myImage.png" forState:UIControlStateNormal];
Businesswoman answered 4/11, 2013 at 1:33 Comment(0)
O
4

This worked for me

[button.imageView setContentMode:UIViewContentModeScaleAspectFit];

Thanks to @ayreguitar for his comment

Offcolor answered 19/3, 2015 at 7:26 Comment(0)
E
4

Here's an alternative answer in swift:

myButton.imageView?.contentMode = .ScaleAspectFit
Echoism answered 29/11, 2015 at 16:4 Comment(0)
S
4

Combining together a few different answers into one solution-- create a button with a custom type, set the button's imageView contentMode property, and set the image for the button (not the background image, which will still scale to fill).

//Objective-C:
UIImage *image = [UIImage imageNamed:"myImageName.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:image forState:UIControlStateNormal];
button.imageView.contentMode = UIViewContentModeScaleAspectFit;

//Swift:
let image = UIImage(named: "myImageName.png")
let button = UIButton(type: .custom)
button.imageView?.contentMode = .scaleAspectFit
button.setImage(image, for: .normal)
Soonsooner answered 18/10, 2016 at 22:51 Comment(0)
A
3

ios 12. You need to add also the content Alignment

class FitButton: UIButton {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)


    }

    override func layoutSubviews() {
        self.imageView?.contentMode = .scaleAspectFill
        self.contentHorizontalAlignment = .fill
        self.contentVerticalAlignment = .fill
        super.layoutSubviews()


    }

}
Adenoid answered 10/2, 2015 at 14:53 Comment(1)
Supposed to be aspect FIT not FILLRoswald
R
3
btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
Rogovy answered 18/3, 2016 at 8:6 Comment(1)
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. - From reviewShewchuk
C
2

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):

UIButtonWithImageAspectFit: create and set image


Then, set its class:

UIButtonWithImageAspectFit: set custom class

You're done!
Instead of
UIButton without image aspect fit
your button's image aspect fit is now as expected:
UIButton with image aspect fit

Clow answered 26/6, 2014 at 9:10 Comment(0)
S
1

UIView content modes apply to the corresponding CALayer's "content". This works for UIImageViews because they set the CALayer content to the corresponding CGImage.

drawRect: ultimately renders to the layer content.

A custom UIButton (as far as I know) has no content (the rounded-rect style buttons might be rendered using content). The button has subviews: the background UIImageView, the image UIImageView, and the title UILabel. Setting the contentMode on the subviews may do what you want, but messing around with the UIButton view hierarchy is a bit of a no-no.

Supersede answered 11/8, 2010 at 18:18 Comment(0)
L
1

I had problems with the image not resizing proportionately so the way I fixed it was using edge insets.

fooButton.contentEdgeInsets = UIEdgeInsetsMake(10, 15, 10, 15);
Ladysmith answered 7/6, 2012 at 7:45 Comment(0)
D
1

Changing UIButton.imageView.contentMode does not worked for me.
I solved the problem by setting the image to 'Background' property.
You can add ratio constraint if you need

Decastro answered 24/12, 2015 at 2:53 Comment(0)
S
1

This overlaps many of the other answers, but the solution for me was to

  • set the contentMode of the UIImageView for the button to .ScaleAspectFit – which can either be done in the ”User Defined Runtime Attributes” in Interface Builder (ie. self.imageView.contentMode, Number, 1) or in a UIButton subclass;
  • disable ”Autoresize Subviews”;
  • set ”Edge” to ”Image” and appropriate ”Top” and ”Bottom” values for ”Inset” (which might only be needed if you, like me, used a PDF as image).
Superinduce answered 17/5, 2016 at 16:57 Comment(0)
D
0

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.

Dibbell answered 20/12, 2010 at 4:47 Comment(0)
O
0

[button sizeToFit] worked for me.

Otalgia answered 17/7, 2012 at 15:42 Comment(0)
R
0

Similar to @Guillaume, I have created a subclass of UIButton as a Swift-File. Then set my custom class in the Interface Builder:

interface builder.

And here the Swift file:

import UIKit

class TRAspectButton : UIButton {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.imageView?.contentMode = .ScaleAspectFit
    }
}
Representation answered 9/8, 2016 at 13:38 Comment(0)
Y
-1

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.

Yves answered 11/8, 2010 at 17:3 Comment(1)
Is there an echo in here? ;-)Minton

© 2022 - 2024 — McMap. All rights reserved.