问题描述
我有一张 tabbarcontroller
,其中一张 tabbaritem
图像显示模糊且质量低。由于此图片是个人资料图片,可能因用户输入而异,I have helper functions to assist in squaring,resizing and rounding the image。
我找不到任何解决此问题的 SO 答案,任何想法将不胜感激。
extension UIImage {
var roundMyImage: UIImage {
let rect = CGRect(origin:CGPoint(x: 0,y: 0),size: self.size)
UIGraphicsBeginImageContextWithOptions(self.size,false,0)
UIBezierPath(
roundedRect: rect,cornerRadius: self.size.height
).addClip()
self.draw(in: rect)
return UIGraphicsGetimageFromCurrentimageContext()!
}
func resizeMyImage(newWidth: CGFloat) -> UIImage {
let scale = newWidth / self.size.width
let newHeight = self.size.height * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth,height: newHeight))
self.draw(in: CGRect(x: 0,y: 0,width: newWidth,height: newHeight))
let newImage = UIGraphicsGetimageFromCurrentimageContext()
UIGraphicsEndImageContext()
return newImage!
}
func squareMyImage() -> UIImage {
UIGraphicsBeginImageContext(CGSize(width: self.size.width,height: self.size.width))
self.draw(in: CGRect(x: 0,width: self.size.width,height: self.size.width))
let newImage = UIGraphicsGetimageFromCurrentimageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
let newImage: UIImage = someImage.squareMyImage().resizeMyImage(newWidth: 24).roundMyImage.withRenderingMode(.alwaysOriginal)
firstTabNav.tabBarItem.image = newImage
firstTabNav.tabBarItem.selectedImage = newImage
解决方法
没有选项的 UIGraphicsBeginImageContext 为您提供了一个比例设置为 1.0 的上下文 - 对于视网膜屏幕,这不是您想要的。如果您使用 UIGraphicsBeginImageContextWithOptions,您可以通过 0.0 进行缩放,并且根据文档:“如果您指定的值为 0.0,则比例因子将设置为设备主屏幕的比例因子”-您似乎在中的比例值不一致squareMyImage、roundMyImage 和 resizeMyImage