![](/img/trans.png)
[英]Asset catalog with PDF Vector Image does not export @3x resolution for iOS
[英]Programmatic scaling of @3x image with UIScreen.main.scale has different result than Asset Catalog
我有一個以@3x
比例從后端返回的圖像。 我希望根據設備以編程方式縮放圖像。 就像是:
let imageSize = CGSize(width: 300, height: 150)
let scale = UIScreen.main.scale / 3.0
let scaledSize = imageSize.applying(CGAffineTransform(scaleX: scale, y: scale))
例如,在 iPhone 6s 模擬器上, UIScreen.main.scale
將為2.0
; 因此生成的scaledSize
將是(2.0 / 3.0) * (width: 300, height: 150) = (width: 200, height: 100)
但是,圖像太大。
我嘗試將相同的@3x
資產添加到資產目錄並直接在代碼中使用它,以找到返回的大小為@1x
(看起來正確)。 因此,在這種情況下,使用 Asset Catalog 會返回大小為(width: 100, height: 50)
的圖像
我是否缺少有關如何UIScreen.main.scale
用於此目的的信息? 以編程方式縮放@3x
圖像的正確方法是什么?
這實際上取決於您為什么要縮放圖像。
如果您在UIImageView
中顯示圖像,它將由 UIKit 自動縮放,因此實際上不需要手動縮放它。
但是,如果您有其他目的……也許您想在設備上保存縮放版本? 也許你正在用它做其他事情?
一種方法是使用UIGraphicsImageRenderer
- 例如:
func resizedImage(from image: UIImage, to scale: CGFloat) -> UIImage? {
if scale == 1.0 {
// don't need to scale the image,
// so just return it
return image
}
let newSize = CGSize(width: image.size.width * scale, height: image.size.height * scale)
let renderer = UIGraphicsImageRenderer(size: newSize)
return renderer.image { (context) in
image.draw(in: CGRect(origin: .zero, size: newSize))
}
}
然后,您可以像這樣縮放圖像:
// using a 300x150 image for demonstration
guard let img = UIImage(named: "bkg300x150") else {
fatalError("Could not load image!!!!")
}
let scale = UIScreen.main.scale / 3.0
guard let scaledImage = resizedImage(from: img, to: scale) else {
fatalError("Image resize failed???")
}
print("Orig:", img.size)
print("Scaled:", scaledImage.size)
iPhone 8 上的 output - @2x 屏幕比例:
Orig: (300.0, 150.0)
Scaled: (200.0, 100.0)
iPhone 13 Pro Max 上的 output - @3x 屏幕比例:
Orig: (300.0, 150.0)
Scaled: (300.0, 150.0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.