[英]UIImage scale factor not taken account of in UITabBarItem image
我正在使用UIGraphicsGetCurrentContext
裁剪UIImage
,然后將其保存到緩存中。 然后我將該 UIImage 顯示為我的選項卡欄項目之一的圖像。 這是有效的,但是,圖像的比例因子是一個問題。 如果我使用UIGraphicsBeginImageContextWithOptions
並將比例設置為零,這將使用屏幕的比例因子正確裁剪它。 但是,當我設置 UITabBarItem 圖像時,它似乎忽略了圖像應該縮放的事實。
我的縮放代碼:
extension UIImage {
func scaledImage(withSize size: CGSize, withBorder: Bool) -> UIImage {
let imageView = UIImageView(image: self)
imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
imageView.contentMode = .scaleAspectFit
let layer = imageView.layer
layer.masksToBounds = true
layer.cornerRadius = size.width/2
if withBorder {
layer.borderColor = Styles.Colours.blue.colour.cgColor
layer.borderWidth = 2
}
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, 1) // Notice I've set the scale factor to 1 here for now. If I set it to 0 the image is too large on the tab bar
defer { UIGraphicsEndImageContext() }
layer.render(in: UIGraphicsGetCurrentContext()!)
return UIGraphicsGetImageFromCurrentImageContext()!
}
}
像這樣使用:
let defaultImage = image?.scaledImage(withSize: CGSize(width: 25, height: 25), withBorder: false)
然后我像這樣設置標簽欄項目:
self.tabBar.items?.last?.image = defaultImage.withRenderingMode(.alwaysOriginal)
如果我要從我的資產設置 UIImage,那么它會考慮比例因子。 我該如何解決? 謝謝!
通過將UIImage
轉換為一個專門定義比例的圖像來解決這個問題:
let scaledSelectedImage = UIImage(data: UIImagePNGRepresentation(image)!, scale: UIScreen.main.scale)
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, 1)
表示您希望以@1x 的比例設置圖像上下文。 如果將其設置為0
它將使用屏幕的原生比例:
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, 0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.