问题
Simple code for resizing image i.e. for navbar (source link) for png image with native res: 722x1028
let imageView = UIImageView(frame: CGRectMake(0, 0, 0, 60))
imageView.image = UIImage(named: "girl")
imageView.contentMode = UIViewContentMode.ScaleAspectFit
self.navigationItem.titleView = imageView
And I get on iPad2:
I can manually render desired image by changing code:
let imageView = UIImageView(frame: CGRectMake(0, 0, 0, 60))
imageView.image = imageWithImage(UIImage(named: "girl")!, scaledToSize: CGSizeMake(42,60))
self.navigationItem.titleView = imageView
func imageWithImage(image:UIImage, scaledToSize newSize:CGSize) -> UIImage{
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
image.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
But this is rather expensive solution.
Is there native library or simple swift solution to make png image automatically resized with good quality?
回答1:
If you have hardcoded size 42x60 points for all devices, the best solution would be to provide pre-rendered image in that size. This is friendly to the battery and allows tweaking the image in a high quality editor before adding to the app: Resizing from 1000 pixels to 60 pixels is a bit drastic and will lead to loss of detail.
If that's not possible (i.e. image is dynamically loaded from the internet etc.), I would start my research with CIImage and CIFilter(name: "CILanczosScaleTransform") which provides very good interpolation quality, possibly followed by CISharpenLuminance if the loss of detail is too high.
来源:https://stackoverflow.com/questions/32673330/resizing-image-for-icons-for-ipad2-swift