UIButton 的 backgroundImage 和 image 的填充模式
来源:互联网 发布:linux shell脚本教程 编辑:程序博客网 时间:2024/05/29 01:54
UIButton 的 backgroundImage 和 image 的填充模式
在将 UIButton 当做图标按钮使用时,可以有两种方式给它设置一张图片:setBackgroundImage:forState:
和 setImage:forState:
。用这两种方式都可以把 UIButton 作为图片按钮使用,这在图片背景的比例和UIButton 的宽高比例相同时是没什么问题的,图片都不会因为被拉伸或者缩放而出现失真。但是当图片的比例和 Button 的尺寸比例不一样时,这两种方式设置图片的效果就不一样了,拿下图的例子来说:
图中 viewController 里 两个 UIButton 的大小都是 100x200,第一个是通过 setImage:forState
设置图片,第二个是通过setBackgroundImage:forState:
设置图片,这张图片的尺寸是 300x428,也就是 Button 和图片的比例不一致。
这时我们不做任何设置,直接运行的话,两个Button的图片都会被拉伸:
这样的效果肯定不是我们想要的,对于setImage:forState:
设置的图片可以给 UIButton 的 imageView
设置对应的填充属性来解决缩放问题,注意不是直接设置 UIButton 的 contentMode,setImage:forState:
会将 image 设置到 UIButton 中的 ImageView 图层,直接设置 UIButton 的 contentMode 是不起作用的。对于用 setBackgroundImage:forState:
方式设置的图片,无论怎么设置都不会有效果,这种方式会直接将图片拉伸至 Button 的边界,来填充满整个 Button。所以如果 图片和 Button的比例不一致时,只能使用 setImage:forState:
这种方式来保证图片不被压缩。
但是,当 Button 的大小超过了图片的原始大小,并且比例也不一样时,这时候 Button 四周就可能会出现图片覆盖不上的空白,例如,现在将上面图中 第一个 Button 的宽度拉大,为了看出效果,这里还为 Button 设置了一个背景颜色:
并且在 viewDidLoad
里加上这一句代码设置图片的填充模式 button1.imageView?.contentMode = .ScaleAspectFill
,再运行看一下效果:
可以发现,设置 button1.imageView?.contentMode = .ScaleAspectFill
的确会让图片不再变形,但是也只是按图片的原始尺寸显示了,两边的留白也是很不美观的。当然,这也是有解决办法的,UIControl 里提供了两个属性:contentHorizontalAlignment
和 contentVerticalAlignment
分别用来设置水平和竖直方向上内容的对齐方式,把 button1 的 contentHorizontalAlignment
设置为 Fill 就可以解决上面的问题,如果是竖直方向无法填满的话,设置 contentVerticalAlignment
就行了,最后来看一下最终的效果:
- UIButton 的 backgroundImage 和 image 的填充模式
- UIButton 的 backgroundImage 和 image 的填充模式
- 22.UIButton的标题和图片位置的调整/Image和BackgroundImage
- C#pictureBox的Image 和BackgroundImage属性的区别
- UIButton的Image和Title的布局
- UIButton的Image和Title的布局
- UIButton.titleLabel.text和[UIButton setTitle:],UIButton.imageView.image和[UIButton setImage]的区别
- UIButton 的 image 和title 位置设置
- 自定义UIButton的title和image位置
- UIButton 调整title和image的位置
- 关于UIButton的IMAGE和TITLE的共存
- [iOS]详解调整UIButton的title和image的位置
- iOS-调整UIButton的title和image的位置
- 详解调整UIButton的title和image的位置
- UIButton和UIImageView中Image拉伸效果的实现
- UIButton上image和title的位置调整
- UIButton不能实现image和title共存的问题
- UIButton通过UIEdgeInsetsMake设置image和title的位置
- HTTP2.0协议
- HQL语句--order by(排序)
- android studio 快捷键修改
- 上传图片前判断图片的尺寸
- 递归和栈的编程1
- UIButton 的 backgroundImage 和 image 的填充模式
- USACO 2009 Dec Bobsledding
- AngularJS RootScope 源码分析
- c语言中的null 和0
- 使用ViewPage时ViewPage中的页面重置问题
- makefile: *** missing separator. Stop
- 冒泡排序和选择排序、快速排序
- Find The First Non Repeated Character In A String : Technical Interview Question
- RobotFramework错误解决:Keyword 'Capture Page Screenshot' could not be run on failure: No browser is open