How to center an image inside an UIButton without stretching in both direction in Swift?(如何在 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.
解决方案是在按钮内使用前景图像时更新 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
这篇关于如何在 UIButton 中居中图像而不在 Swift 中双向拉伸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 UIButton 中居中图像而不在 Swift 中双向拉伸?
基础教程推荐
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
