为什么自定义 UIButton 图像不随按钮调整大小?
我将其视图模式设置为Scale to Fill in Interface Builder,但与 UIImageView 图像不同,它不尊重该设置。
我是在找错地方还是不可能?
为什么自定义 UIButton 图像不随按钮调整大小?
我将其视图模式设置为Scale to Fill in Interface Builder,但与 UIImageView 图像不同,它不尊重该设置。
我是在找错地方还是不可能?
虽然这可能不是您所追求的 - 背景图像确实会缩放。
尝试这个:
[button setImage:image forState:UIControlStateNormal];
button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
在斯威夫特:
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
我知道这很旧,但我认为正确的答案是您应该将内容模式设置为 UIButton 内的“隐藏”UIImageView:
button.imageView.contentMode = UIViewContentModeScaleAspectFill;
这将更改图像集的图像视图的内容模式:
[button setImage:yourAwesomeImage forState:UIControlStateNormal];
//Or any other state
只是做(从设计或从代码):
[对于第 3 点:将水平和垂直对齐更改为 UIControlContentHorizontalAlignmentFill 和 UIControlContentVericalAlignmentFill]
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill; button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
界面生成器
要让 UIButtons 中的图像以与界面 Builder 中的 UIViews 相同的方式缩放,请执行以下步骤:
选择您的 UIButton 并从Identity Inspector中将以下内容添加到 User Defined Runtime Attributes:
imageView.contentMode 编号 1
其中 number 是 contentMode 的枚举数,例如:
0 = Scale to fill
1 = Aspect Fit
2 = Aspect Fill
etc..
然后打开UIButton的属性编辑器,在Control下将Alignment设置为 Fill(右侧的最后一个按钮),用于水平和垂直。
斯威夫特 3
请注意,您也可以使用以下代码在代码中执行此操作:
button.imageView?.contentMode = .scaleAspectFit
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
更新这篇文章将为 Swift 5 提供完整答案:
//Set button's image
let image = UIImage(systemName: "heart.fill") //Your image here
button.setImage(image, for: .normal)
//Optional: Remove background image if you added one on accident
button.setBackgroundImage(nil, for: .normal)
//Optional: Set button's title (displayed next to button's image)
button.setTitle(nil, for: .normal)
//The button's "content" includes the title label and image
//So we set the button's content to fill the button
//If title label is nil, the content will only show the image
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
//Set button's image to desired content mode (aspectFit avoids distortion)
//This restricts the image from resizing to fill the entire content area
button.imageView?.contentMode = .scaleAspectFit
尝试将 Interface Builder 中的 Clip subviews 属性设置为 true。
希望有帮助。
到目前为止,我在 Swift 2.1 中找到的最佳解决方案如下:
self.imageButton.imageView?.clipsToBounds = true
self.imageButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
这将缩放图像,使其具有适合 imageView 的方面。
只需获取一个真正的 UIimageview 并在其顶部放置一个 UIbutton 并通过布局菜单将其设置为后退即可。然后您可以正确缩放图像。