我遇到了一个奇怪的问题,在UIImageView中显示了一个UIImage。
如果我将一个1024x1024图像放在173x173图像视图中并设置了“缩放以填充”,则结果是别名。但是,如果我放入相同的图像,然后截取图像视图的屏幕截图并将其分配回来,图像将完美显示。这让我感到困扰,因为屏幕截图应该是我在图像视图中看到的精确像素。
左侧是直接分配图像的结果。在右侧是截取相同图像的屏幕截图并将其分配回来。注意Es在左边是锯齿状的,但在右边是平滑的。
这是图像视图的内容模式或者在sreenshot期间发生的事情的问题吗?
for(UIImageView* placeholderView in self.placeholderImageViews)
{
//assigning a 1024x1024 image into a smaller image view results in an aliased image here
placeholderView.image = imageToDisplay;
//this code makes the image appear perfectly scaled down
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
{
UIGraphicsBeginImageContextWithOptions(placeholderView.frame.size, NO, [UIScreen mainScreen].scale);
}
else
{
UIGraphicsBeginImageContext(placeholderView.frame.size);
}
[placeholderView.layer renderInContext:UIGraphicsGetCurrentContext()];
screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//save the result
placeholderView.image = screenshot;
}
答案 0 :(得分:0)
UIImageView缩放很糟糕;你应该总是给它一个与其边界大小完全相同的图像,所以它不必缩小它。 检查此代码和示例。
Swift扩展名:
extension UIImage{
// returns a scaled version of the image
func imageScaledToSize(size : CGSize, isOpaque : Bool) -> UIImage{
// begin a context of the desired size
UIGraphicsBeginImageContextWithOptions(size, isOpaque, 0.0)
// draw image in the rect with zero origin and size of the context
let imageRect = CGRect(origin: CGPointZero, size: size)
self.drawInRect(imageRect)
// get the scaled image, close the context and return the image
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
}
示例:
aUIImageView.image = aUIImage.imageScaledToSize(aUIImageView.bounds.size, isOpaque : false)
如果图像没有alpha,则将isOpaque设置为true:绘图将具有更好的性能。