Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center an image inside an UIButton without stretching in both direction in Swift?

I am making a custom keyboard and I need to centre the image of the shift icon inside the shift button. The image is 100px x 100px.

However, the button frame in portrait is 36pt x 38pt, and in landscape, it is 68pt x 32pt. I have tried using button image inset property to centre the image. However, it does not does so.

I tried myself and set the image edge insets to (25,25,25,25), the image centres in both sizes. However, the icon becomes too small to see.

shiftButton.setImage(UIImage(named: "shift"), forState: .Normal)  shiftButton.imageEdgeInsets = UIEdgeInsetsMake(0,0,0,0) 

I am making the button programatically. And, I need the button to scale maintaining its aspect ratio i.e. 1:1. Its maximum width or height is always tied to the button's height itself. The image width/height should be maximum of button's height. And, it should not stretch in any way to distort the icon. However, the button itself can stretch.

I need the image to scale according to button frame but maintain its aspect ratio. And, it can down scale or up scale, but should always maintain the 1:1 aspect ratio.

Any suggestions for solving this problem?

like image 543
Ariel Avatar asked Aug 01 '16 10:08

Ariel


People also ask

How do you center an image in UIButton?

You must set the content mode for the image inside the UIButton. The solution is to update the contentMode of the Image when you are using a foreground image inside a button along with the contentMode of the UIButton .

How do I center an image in Xcode?

Select your image view and apply width and height constraints via the pin dialogue box (screenshot below), then open your alignment constraints and select center horizontally and center vertically. Then just apply your constraints and voila!

How do I put the image on the right side of the text in a UIButton?

To make an UIButton's image align to the right side of the text, we force content flipping behavior to the one use it right-to-left language. 1 By adding this semanticContentAttribute = . forceRightToLeft , we force UIKit to mirrored our content which push our image to the right side of the text. Here is the result.


2 Answers

Finally a solution came through. You must set the content mode for the image inside the UIButton.

The solution is to update the contentMode of the Image when you are using a foreground image inside a button along with the contentMode of the UIButton.

shiftButton.contentMode = .Center shiftButton.imageView?.contentMode = .ScaleAspectFit 
like image 55
Ariel Avatar answered Sep 16 '22 16:09

Ariel


If you're using storyboard, double-check that you don't have anything set for the button title.

like image 44
Scott Zhu Avatar answered Sep 20 '22 16:09

Scott Zhu