首页 > 解决方案 > UIImageView 中的矢量图像在 iOS 12 和 13 中呈现不同

问题描述

我在我的 xcassets 中使用了一些 pdf 图像,并选中了“保留矢量数据”。相同的图像在不同的 iOS 版本(我使用的是 Xcode 11.2)中呈现不同。在左侧,图像在 iOS 13.2 中按预期呈现,在右侧,图像在 iOS 11.4 中未按预期呈现(在 iOS 12.2 中相同)。通过取消对“保留矢量数据”的检查,问题不会出现。

在此处输入图像描述

创建 UIImageViews 的代码是这样的:

    self.view.backgroundColor = .white
    let imageView = UIImageView(frame: CGRect(x: 10, y: 20, width: self.view.bounds.width - 20, height: self.view.bounds.width - 20))
    imageView.image = UIImage(named: "calendar")
    imageView.backgroundColor = UIColor.red.withAlphaComponent(0.4)
    imageView.contentMode = .center
    self.view.addSubview(imageView)

Pdf 图像大小为 27x23 像素,通过停止模拟器并打印出图像大小和比例仍然可以打印正确的值:

(lldb) po ((UIImageView *) 0x7fa1b0c053e0).image.scale
2

(lldb) po ((UIImageView *) 0x7fa1b0c053e0).image.size
(width = 27, height = 23)

我错过了什么吗?

标签: iosxcodeuiimageviewxcassetcontentmode

解决方案


我知道这听起来很奇怪,但是 UIImageView 属性设置中的一个小开关可以解决这个问题:

let imageView = UIImageView(frame: CGRect(x: 10, y: 20, width: self.view.bounds.width - 20, height: self.view.bounds.width - 20))
imageView.contentMode = .center
imageView.image = UIImage(named: "calendar")
imageView.backgroundColor = UIColor.red.withAlphaComponent(0.4)
self.view.addSubview(imageView)

先设置contentMode,再设置image


推荐阅读