如何在Swift中将图像居中而不在两个方向上都在UIButton中居中? [英] How to center an image inside an UIButton without stretching in both direction in Swift?
问题描述
我正在制作自定义键盘,我需要将Shift图标的图像居中于Shift按钮内.图片为100像素x 100像素.
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.
但是,纵向的按钮框为 36pt x 38pt
,而在横向的按钮框为 68pt x 32pt
.我尝试使用按钮图像插入属性将图像居中.但是,事实并非如此.
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.
我尝试了一下,并将图像边缘插图设置为(25,25,25,25)
,图像的中心在这两种尺寸下.但是,图标变得太小而看不到.
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)
我正在按编程方式制作按钮.而且,我需要该按钮缩放比例以保持其宽高比,即 1:1
.其最大宽度或高度始终与按钮本身的高度相关.图片宽度/高度应为按钮高度的最大值.并且,它不应以任何方式拉伸以使图标变形.但是,按钮本身可以拉伸.
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.
我需要根据按钮框缩放图像,但要保持其宽高比.而且,它可以缩小或放大,但应始终保持1:1的宽高比.
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?
推荐答案
最后解决了一个问题.您必须在UIButton内设置图像的内容模式.
Finally a solution came through. You must set the content mode for the image inside the UIButton.
解决方案是,当您在按钮内使用前景图像以及菜单的 contentMode
时,更新 Image
的 contentMode
. 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
这篇关于如何在Swift中将图像居中而不在两个方向上都在UIButton中居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!