简体   繁体   English

iOS自定义UIButton缩放setImage向下不起作用

[英]ios Custom UIButton scale setImage down not working

I have problem in scale down setImage size if I add UIButton by programmatically whereas if I add the UIButton by storyboard, the UIButton size remain correctly. 如果按编程方式添加UIButton,则在缩小setImage大小时遇到​​问题,而如果按故事板添加UIButton,则UIButton大小保持正确。 The Image is 128x128, I want to shrink down to 30x30 图片为128x128,我想缩小到30x30

在此处输入图片说明 Top one is created from using storyboard, Bottom is created from using programmatically 顶部是通过使用情节提要创建的,底部是通过以编程方式创建的

These are the methods I tried, none able to shrink the image... 这些是我尝试过的方法,无法缩小图像...

let checkBox = UIButton(type .system) 
checkBox.sizeThatFits(CGSize(width: 30, height: 30))
checkBox.contentMode = .scaleAspectFit
checkBox.contentVerticalAlignment = .fill
checkBox.contentHorizontalAlignment = .fill
checkBox.heightAnchor.constraint(equalToConstant: 15.0)
checkBox.widthAnchor.constraint(equalToConstant: 15.0)     

Image is set/update on runtime checkBox.setImage(UImage, for: .normal) 在运行时checkBox.setImage(UImage,for:.normal)上设置/更新图像

With suggest using checkBox.frame.size.width, checkBox.frame.size.height the image becomes correct size but the UIButton now have extra space. 通过使用checkBox.frame.size.width,checkBox.frame.size.height的建议,图像变为正确的大小,但是UIButton现在具有额外的空间。 Like the image below. 如下图所示。 I update image on touchUP UIButton 我在touchUP UIButton上更新图像 在此处输入图片说明

What about this: 那这个呢:

checkBox.frame.size.width = 30
checkBox.frame.size.height = 30

The Image is 128x128, I want to shrink down to 30x30 图片为128x128,我想缩小到30x30

One obvious solution, in that case, is to shrink the image . 在这种情况下,一种显而易见的解决方案是缩小图像 Redraw the image into a 30x30 graphics context at 30x30 size and extract the resulting image. 以30x30的大小将图像重新绘制到30x30的图形上下文中,并提取生成的图像。 Now you have a 30x30 image. 现在您有了30x30的图片。 That's the best way; 那是最好的方法; it is a waste of memory to hand the runtime a way oversized image and ask it to display it smaller. 将运行时处理过大的图像并要求其缩小显示是浪费内存的。

Now, if you want to use constraints to size and position the button, that's fine, but you are not doing that correctly. 现在,如果您想使用约束来调整按钮的大小和位置,那很好,但是您这样做的方式不正确。 First, you have forgotten to set the button's translatesAutoresizingMaskIntoConstraints to false . 首先,您忘记将按钮的translatesAutoresizingMaskIntoConstraints设置为false Second, you have to supply enough constraints not only to set the button's height and width but also its horizontal and vertical position. 其次,您必须提供足够的约束,不仅要设置按钮的高度和宽度,还要设置按钮的水平和垂直位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM