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:
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.
UIImage *img = [UIImage imageNamed:@"anyImageName"];
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.
UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .
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.
UIButton is broken. That's the short answer. The UIImageView
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With