ios 如何在 UIButton 中居中图像而不在 Swift 中双向拉伸?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38697032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to center an image inside an UIButton without stretching in both direction in Swift?
提问by Ariel
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.
我正在制作一个自定义键盘,我需要将 shift 按钮内的 shift 图标的图像居中。图像为 100 像素 x 100 像素。
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.
但是,纵向的按钮框是36pt x 38pt
,横向的则是68pt x 32pt
。我曾尝试使用按钮图像插入属性来居中图像。然而,它并没有这样做。
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.
我尝试了自己并将图像边缘插入设置为(25,25,25,25)
,两种尺寸的图像中心。但是,图标变得太小而无法看到。
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.
我正在以编程方式制作按钮。而且,我需要按钮来缩放保持其纵横比,即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.
我需要根据按钮框架缩放图像但保持其纵横比。而且,它可以缩小或放大,但应始终保持 1:1 的纵横比。
Any suggestions for solving this problem?
有什么建议可以解决这个问题吗?
回答by Ariel
Finally a solution came through. You must set the content mode for the image inside the UIButton.
终于有办法解决了。您必须为 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
.
该解决方案是更新contentMode
的Image
,当你与一起使用按钮内的前景图像contentMode
的UIButton
。
shiftButton.contentMode = .Center
shiftButton.imageView?.contentMode = .ScaleAspectFit
回答by Prateep Gedupudi
回答by Scott Zhu
If you're using storyboard, double-check that you don't have anything set for the button title.
如果您使用的是故事板,请仔细检查您没有为按钮标题设置任何内容。
回答by Justin Vallely
回答by Viktor Simkó
Set the button's content mode to Center
:
将按钮的内容模式设置为Center
:
shiftButton.contentMode = .Center