Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simple way to put a UIImage in a UIButton

I have a UIButton in my iPhone app. I set its size to 100x100.

I have an image that is 400x200 that I wish to display in the button.

The button STILL needs to stay at 100x100... and I want the image to downsize to fit... but keep the correct aspect ratio.

I thought that's what "Aspect Fit" was used for.

Do I include my image with setImage, or setBackgroundImage?

Do I set AspectFit for the button? or the image? or the background image?

(I need the smaller images to INCREASE in size. While larger images should DESCREASE in size. Always keeping the button at 100x100.)

I've tried countless combinations of all of the above... and I just can't seem to get everything to work at the same time:

  • Don't change the button's size of 100x100.
  • Don't destroy the image's aspect ratio.
  • Always increase small images to fit the button.
  • Always decrease large images to fit the button.
  • Never clip any of the image edges.
  • Never require the "put UIButtons over all your UIimages" hack.
  • Don't require everyone to upgrade to v4.2.1 just to use new framework methods.

I see so many apps, with so many fully-working image-buttons... that I can't believe I can't figure out this very simple, very common thing.

Ugh.

like image 954
Alice Avatar asked Dec 21 '10 17:12

Alice


People also ask

How do you add a UIImage in Objective C?

UIImage *img = [UIImage imageNamed:@"anyImageName"];

How do I add a UIImage in Xcode?

Drag and drop image onto Xcode's assets catalog. Or, click on a plus button at the very bottom of the Assets navigator view and then select “New Image Set”. After that, drag and drop an image into the newly create Image Set, placing it at appropriate 1x, 2x or 3x slot.

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .

How do I find my UIImage path?

Once a UIImage is created, the image data is loaded into memory and no longer connected to the file on disk. As such, the file can be deleted or modified without consequence to the UIImage and there is no way of getting the source path from a UIImage.


1 Answers

UIButton is broken. That's the short answer. The UIImageViews in its image and backgroundImage properties don't respect UIViewContentMode settings. They're read-only properties, and while the UIImage contents of those UIImageViews can be set through setImage: and setBackgroundImage: methods, the content mode can't be.

The solution is either to provide properly-sized images in your bundle to begin with, or to put a UIImageView down, configure it the way you want it, and then put a clear "custom" UIButton over top of it. That's the hack all those fancy professional apps you've seen have used, I promise. We're all having to do it.

like image 82
Dan Ray Avatar answered Sep 22 '22 06:09

Dan Ray