Ios UIAbbarItem图像中未考虑UIImage比例因子
我正在使用Ios UIAbbarItem图像中未考虑UIImage比例因子,ios,swift,Ios,Swift,我正在使用UIGraphicsGetCurrentContext裁剪UIImage,然后将其保存到缓存中。然后,我将UIImage显示为一个选项卡栏项目的图像。这是可行的,但是,图像的比例因子是一个问题。如果我使用UIGraphicsBeginImageContextWithOptions并将比例设置为零,这将使用屏幕的比例因子正确地裁剪它。但是,当我设置UITabBarItem图像时,它似乎忽略了图像应该缩放的事实 我的缩放代码: extension UIImage { func sc
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)
let scaledSelectedImage = UIImage(data: UIImagePNGRepresentation(image)!, scale: UIScreen.main.scale)
然后我将选项卡栏项设置为:
let defaultImage = image?.scaledImage(withSize: CGSize(width: 25, height: 25), withBorder: false)
self.tabBar.items?.last?.image = defaultImage.withRenderingMode(.alwaysOriginal)
let scaledSelectedImage = UIImage(data: UIImagePNGRepresentation(image)!, scale: UIScreen.main.scale)
如果我要从我的资产设置UIImage,那么它将考虑比例因子。我该如何解决这个问题?谢谢
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size,false,1)
表示希望将图像上下文设置为@1x的比例。如果将其设置为0
,则使用屏幕的本机比例:
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size,false,0)
通过将UIImage
转换为专门定义比例的图像来解决此问题,如下所示:
let defaultImage = image?.scaledImage(withSize: CGSize(width: 25, height: 25), withBorder: false)
self.tabBar.items?.last?.image = defaultImage.withRenderingMode(.alwaysOriginal)
let scaledSelectedImage = UIImage(data: UIImagePNGRepresentation(image)!, scale: UIScreen.main.scale)
是的,但当我设置选项卡栏项目图像时,图像比例因子并没有考虑到结果UIImage的比例是多少?将它设置为
1
肯定不会给你一个可以在@2x或@3x设备上缩放的图像,我可以说很多。是的,我知道,这就是为什么我在那行旁边放了一条评论。我的设备的比例因子是@3x