低质量 TabBarItem 图像

Low Quality TabBarItem Image

我有一张 tabbarcontroller,其中一张 tabbaritem 图片显示模糊且质量低下。由于此图片是个人资料图片,可能会因用户输入而异,

我找不到任何解决此问题的 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, y: 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