0

I have a button with an image inside, but I want to adjust the size of this image, how can I adjust the size of the image? I'm trying to make my image 150 points high, but I do not know how to do it programmatically

enter image description here

5
  • How are you creating your UI? Are you using storyboards or doing it programmatically?
    – HAK
    May 23, 2018 at 18:38
  • @HAK i am using storyboards May 23, 2018 at 18:39
  • And how are you setting your images? Dynamically?
    – HAK
    May 23, 2018 at 18:42
  • @HAK no, I'm placing my image with the property of the buttons, the property image May 23, 2018 at 18:44
  • Cant you use UIImageView instead of buttons. UIImageView has a property to fit the image with respect to the aspect ratio so the image won't stretch.
    – HAK
    May 23, 2018 at 18:50

2 Answers 2

1

The best possible approach would be to regenerate the image asset at the appropriate size you need it (using photoshop, preview, etc) and then use that instead.

Another option, in the storyboard switch to the ruler tab and adjust the image insets.

image insets

Yet another approach would be to use a UIImageView and add a UITapGestureRecognizer to it to detect a tap. Then you can configure the image view with constraints and set up the aspect ratio. The downside here is that you lose the stateful changes of the button when it is pressed/depressed so it won't look as good. I wouldn't add an imageview as a subview of a button either, that can create strange problems.

One thing I'd like to add is that resizing images can be expensive. If you are loading these buttons into a tableview then you need to be careful not to accidentally resize the images as the cells are enqueued/dequeued. This will block the main thread and cause smooth scrolling issues.

0

When you set a button’s image it will have an imageView property containing the image. Therefore, you can set the imageView’s contentMode property to .scaleAspectFit to keep the image proportions after resizing:

button.imageView?.contentMode = .scaleAspectFit

The actual resizing can be done in InterfaceBuilder using layout constraints, for example.

However, if you know the button target size at compile time, you should make sure the image already has the desired size instead of sizing a wrongly-sized image at runtime.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.