添加 UIImage 忽略并调整 UIImageView 框架的大小 [英] Adding UIImage ignores and resizes UIImageView frame
问题描述
我目前正在尝试将图像添加到一个视图的导航项中.在视图的viewDidLoad()
中,调用了一个函数,代码如下,类似于
从 UIImageView 中移除 UIImage 会使视图大小正确,如下所示:
这对我来说似乎很奇怪,尤其是因为我确实将内容模式设置为 .scaleAspectFit
.关于将 UIImageView
添加为 navigationItem.titleView
,我是否忘记了什么?
在 UINavigationBar
上,如果内容很大,标题视图将显示其完整大小.
调整图像大小而不是 UIImageView
如下,传递大小 (122, 26).这将解决您的问题.
func imageResize(sizeChange: CGSize) ->用户界面{让 hasAlpha = truelet scale: CGFloat = 0.0//使用主屏幕的比例因子UIGraphicsBeginImageContextWithOptions(sizeChange, !hasAlpha, scale)self.draw(in: CGRect(origin: CGPoint.zero, size: sizeChange))让 scaledImage = UIGraphicsGetImageFromCurrentImageContext()返回缩放图像!}
I'm currently trying to add an image into the navigation item for one view. In the view's viewDidLoad()
, a function is called with the following code, similar to this post:
let logo = UIImage(named: "Menu_Logo")
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 122, height: 26))
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
imageView.image = logo
self.navigationItem.titleView = imageView
Instead of giving me the expected size however, the view ends up looking like this:
Removing the UIImage from the UIImageView makes the view sized correctly like this:
This seems like strange behaviour to me, especially since I did set the content mode to .scaleAspectFit
. Is there something I am forgetting regarding adding an UIImageView
as the navigationItem.titleView
?
On UINavigationBar
, title view takes its full size, if content is large.
Resize the image rather than
UIImageView
as following with passing size (122, 26). This will solve your problem.
func imageResize(sizeChange: CGSize) -> UIImage {
let hasAlpha = true
let scale: CGFloat = 0.0 // Use scale factor of main screen
UIGraphicsBeginImageContextWithOptions(sizeChange, !hasAlpha, scale)
self.draw(in: CGRect(origin: CGPoint.zero, size: sizeChange))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
return scaledImage!
}
这篇关于添加 UIImage 忽略并调整 UIImageView 框架的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!