我使用UIImage
裁剪UIGraphicsGetCurrentContext
,然后将其保存到缓存中。然后我将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,那么它会考虑比例因子。我该如何解决?谢谢!
答案 0 :(得分:0)
通过将UIImage
转换为专门定义比例的那个来解决它:
let scaledSelectedImage = UIImage(data: UIImagePNGRepresentation(image)!, scale: UIScreen.main.scale)
答案 1 :(得分:-1)
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, 1)
表示您希望将图像上下文设置为@ 1x的比例。如果将其设置为0
,则使用屏幕的原始比例:
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, 0)