113

I want to add an image to a UIButton, and also want to scale my image to fit with the UIButton (make image smaller). Please show me how to do it.

This is what I have tried, but it does't work:

  • Adding image to button and using setContentMode:
[self.itemImageButton setImage:stretchImage forState:UIControlStateNormal];
[self.itemImageButton setContentMode:UIViewContentModeScaleAspectFit];
  • Making a "stretch image":
UIImage *stretchImage = [updatedItem.thumbnail stretchableImageWithLeftCapWidth:0 topCapHeight:0];
Ortwin Gentz
  • 52,648
  • 24
  • 135
  • 213
KONG
  • 7,271
  • 6
  • 28
  • 27

17 Answers17

210

I had the same problem. Just set the ContentMode of the ImageView that is inside the UIButton.

[[self.itemImageButton imageView] setContentMode: UIViewContentModeScaleAspectFit];
[self.itemImageButton setImage:[UIImage imageNamed:stretchImage] forState:UIControlStateNormal];
starball
  • 20,030
  • 7
  • 43
  • 238
Dave
  • 7,552
  • 4
  • 22
  • 26
  • 15
    Make sure you're setting the **imageView**. I also failed to notice, for a bit, that I was still using the backgroundImageView and it wasn't working for that. – Alexandre Gomes Mar 29 '11 at 16:17
  • 2
    It seems this method has some problems when the button state is 'highlighted'. The image will back to the fill mode. Any idea? – Yuanfei Zhu Feb 23 '12 at 18:47
  • It is not working to me. However, I make it work by using [self.itemImageButton setbackgroundImage:[UIImage imageNamed:stretchImage] forState:UIControlStateNormal]; – Mickey Dec 09 '12 at 07:21
  • 3
    This worked for me. I set the content mode as above. However, you also need to set the same image of the highlighted state in order to avoid the image going back to "fill mode". For example, [imageButton setImage:image forState:UIControlStateHighlighted]; – Christopher Jan 11 '13 at 04:54
  • @Dave from Apple doc about imageView **The button’s image view. (read-only)** that's why it does not work – onmyway133 Dec 11 '13 at 04:51
  • 2
    You can do this in Interface Builder with key path `imageView.contentMode`, type `Number`, and value `1` – bendytree Apr 23 '15 at 01:12
  • apple help for how to do "bendytree" comment process in Interface Builder - https://developer.apple.com/library/mac/recipes/xcode_help-interface_builder/Chapters/AddUserDefinedRuntimeAttributes.html – SHS Aug 20 '15 at 06:19
125

None of the answers here really worked for me, I solved the problem with the following code:

button.contentMode = UIViewContentModeScaleToFill;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;

You can do this in the Interface Builder as well.

enter image description here

Pang
  • 9,564
  • 146
  • 81
  • 122
nalexn
  • 10,615
  • 6
  • 44
  • 48
64

The easiest way to programmatically set a UIButton imageView in aspect fit mode :

Swift

button.contentHorizontalAlignment = .fill
button.contentVerticalAlignment = .fill
button.imageView?.contentMode = .scaleAspectFit

Objective-C

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
button.imageView.contentMode = UIViewContentModeScaleAspectFit;

Note: You can change .scaleAspectFit (UIViewContentModeScaleAspectFit) to .scaleAspectFill (UIViewContentModeScaleAspectFill) to set an aspect fill mode

Tanguy G.
  • 2,143
  • 19
  • 18
  • 1
    This is the only solution I've found that works. The key is the content*Alignment calls. It also works inside UIStackViews. Thank you! –  Jun 25 '22 at 18:03
27

If you really want to scale an image, do it, but you should resize it before using it. Resizing it at run time will just lose CPU cycles.

This is the category I'm using to scale an image :

UIImage+Extra.h

@interface UIImage (Extras)
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
@end;

UIImage+Extra.m

@implementation UIImage (Extras)

- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {

UIImage *sourceImage = self;
UIImage *newImage = nil;

CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;

CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;

CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;

CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

if (!CGSizeEqualToSize(imageSize, targetSize)) {

        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;

        if (widthFactor < heightFactor) 
                scaleFactor = widthFactor;
        else
                scaleFactor = heightFactor;

        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;

        // center the image

        if (widthFactor < heightFactor) {
                thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
        } else if (widthFactor > heightFactor) {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
}


// this is actually the interesting part:

UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0);

CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width  = scaledWidth;
thumbnailRect.size.height = scaledHeight;

[sourceImage drawInRect:thumbnailRect];

newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

if(newImage == nil) NSLog(@"could not scale image");


return newImage ;
}

@end

You can use it to the size you want. Like :

[self.itemImageButton setImage:[stretchImage imageByScalingProportionallyToSize:CGSizeMake(20,20)]];
gcamp
  • 14,622
  • 4
  • 54
  • 85
  • Thanks for your answer, Gcamp. I did have an method for resizing by ratio. But I still try to find a way to tell UIButton do it for me. My image is load from Internet so I can't resize it at compile time. BTW, thank you very much for your response. – KONG Jan 08 '10 at 04:26
  • 2
    Because the image is placed into a CALayer, rendered, and cached by Quartz, performance should not be any worse if you place it in there at full size. Either way, you're resizing ~1 time. gcamp's answer is much more important if you're constantly resizing the button or doing other things that would trigger Quartz to redraw the image layer. – Ben Gotow Dec 31 '11 at 06:36
  • it seems like image quality is reduced. i am testing on iphone 6 plus. Is it true? I also have 3x image. – Khant Thu Linn Feb 23 '15 at 08:56
  • Yes it will, this code is pretty old. It was `UIGraphicsBeginImageContext` instead of `UIGraphicsBeginImageContextWithOptions`. Just fixed it. – gcamp Feb 23 '15 at 20:25
  • yeah but in many cases it doesn't matter if you loose a few cycles, so no point in filling up the ram – Radu Simionescu Jan 29 '16 at 17:20
22

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);
ninjaneer
  • 6,951
  • 8
  • 60
  • 104
17

This can now be done through IB's UIButton properties. The key is to set your image as a the background, otherwise it won't work.

enter image description here

capikaw
  • 12,232
  • 2
  • 43
  • 46
14

Expanding on Dave's answer, you can set the contentMode of the button's imageView all in IB, without any code, using Runtime Attributes:

enter image description here

  • 1 means UIViewContentModeScaleAspectFit,
  • 2 would mean UIViewContentModeScaleAspectFill.
Ortwin Gentz
  • 52,648
  • 24
  • 135
  • 213
13

1 - clear Button default text (important)

2 - set alignment like image

3 - set content mode like image

enter image description here

Hamid Reza Ansari
  • 1,107
  • 13
  • 16
8

If you simply want to reduce your button image:

yourButton.contentMode = UIViewContentModeScaleAspectFit;
yourButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
Tulleb
  • 8,919
  • 8
  • 27
  • 55
6

I have a method that does it for me. The method takes UIButton and makes the image aspect fit.

-(void)makeImageAspectFitForButton:(UIButton*)button{
    button.imageView.contentMode=UIViewContentModeScaleAspectFit;
    button.contentHorizontalAlignment=UIControlContentHorizontalAlignmentFill;
    button.contentVerticalAlignment=UIControlContentVerticalAlignmentFill;
}
Abedalkareem Omreyh
  • 2,180
  • 1
  • 16
  • 20
5

Swift 5.0

 myButton2.contentMode = .scaleAspectFit
 myButton2.contentHorizontalAlignment = .fill
 myButton2.contentVerticalAlignment = .fill
Matthew
  • 1,905
  • 3
  • 19
  • 26
Qasim Mirza
  • 71
  • 1
  • 2
4

The cleanest solution is to use Auto Layout. I lowered Content Compression Resistance Priority of my UIButton and set the image (not Background Image) via Interface Builder. After that I added a couple of constraints that define size of my button (quite complex in my case) and it worked like a charm.

Rudolf Adamkovič
  • 31,030
  • 13
  • 103
  • 118
  • This worked for me -- but only if I selected to use the "Background Image", not the actual image. Whatever works! This was driving me NUTS. – Andy Feb 13 '15 at 02:53
  • Under Xcode 6.2 this worked for me but like @AndrewHeinlein said, used `Background Image` – RoLYroLLs Apr 16 '15 at 03:32
4

in xCode 13.4.1, configure Style to Default and State Config to Default

enter image description here

Md. Ibrahim Hassan
  • 5,359
  • 1
  • 25
  • 45
Omar N Shamali
  • 503
  • 5
  • 11
3

make sure that you have set the image to Image property, but not to the Background

andrew
  • 39
  • 1
2

Background image can actually be set to scale aspect fill pretty easily. Just need to do something like this in a subclass of UIButton:

- (CGRect)backgroundRectForBounds:(CGRect)bounds
{
    // you'll need the original size of the image, you 
    // can save it from setBackgroundImage:forControlState
    return CGRectFitToFillRect(__original_image_frame_size__, bounds);
}

// Utility function, can be saved elsewhere
CGRect CGRectFitToFillRect( CGRect inRect, CGRect maxRect )
{
    CGFloat origRes = inRect.size.width / inRect.size.height;
    CGFloat newRes = maxRect.size.width / maxRect.size.height;

    CGRect retRect = maxRect;

    if (newRes < origRes)
    {
        retRect.size.width = inRect.size.width * maxRect.size.height / inRect.size.height;
        retRect.origin.x = roundf((maxRect.size.width - retRect.size.width) / 2);
    }
    else
    {
        retRect.size.height = inRect.size.height * maxRect.size.width / inRect.size.width;
        retRect.origin.y = roundf((maxRect.size.height - retRect.size.height) / 2);
    }

    return retRect;
}
Andy Poes
  • 1,682
  • 15
  • 19
1

For Xamarin.iOS (C#):

    myButton.VerticalAlignment = UIControlContentVerticalAlignment.Fill;
    myButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Fill;
    myButton.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit;
Mobile Developer
  • 5,730
  • 1
  • 39
  • 45
-1

You just need to set content mode of UIButton imageview for three events. -

[cell.button setImage:[UIImage imageWithData:data] forState:UIControlStateNormal];

[cell.button setImage:[UIImage imageWithData:data] forState:UIControlStateHighlighted];

[cell.imgIcon setImage:[UIImage imageWithData:data] forState:UIControlStateSelected];

We have code for three event bcoz while highlighting or selecting if button size is SQUARE and image size is rectangle then it will show square image at the time of highlighting or selecting.

I am sure it will work for you.

Dhruv
  • 2,153
  • 3
  • 21
  • 45
ruyamonis346
  • 357
  • 3
  • 15
  • You're not setting a content mode, you're setting the image. And they're not events, they're states. You're making a big mess. This is totally unrelated to the question. – manecosta Jul 07 '14 at 21:08