如何在 UIButton 中居中图像而不在 Swift 中双向拉伸? [英] How to center an image inside an UIButton without stretching in both direction in Swift?

查看:20
本文介绍了如何在 UIButton 中居中图像而不在 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.

解决方案是在按钮内使用前景图像时更新 ImagecontentMode 以及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

这篇关于如何在 UIButton 中居中图像而不在 Swift 中双向拉伸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆