保存UIIView到图像,存储在磁盘上,然后重新显示视网膜
问题描述:
我有一个相当复杂的工作流程,遇到了视网膜显示问题。我有一个可以包含19个子视图的滚动视图。这些子视图中的每一个都由几个不同的组件(几个UILabels,一个UIImageView和一些UIButtons)组成。在任何给定时间,屏幕上都有多个滚动视图,可能有数百个子视图。为了节省开销,我在内存中创建了每个子视图,然后将其平铺到UIImage中,该UIImage仍在内存中。从那里我使用UIImage作为子视图来显示。保存UIIView到图像,存储在磁盘上,然后重新显示视网膜
作为另一个节省成本的步骤,我决定将这些UIImage合成后保存到磁盘中,将路径存储在核心数据中,然后将它们从磁盘中取出,而不是一直重新创建它们。所以,我首先检查磁盘以查看该文章的图像是否存在。如果没有,我创建它,将它保存到磁盘并显示在屏幕上。
这里是我正在完成此步骤:
// create ViewController (cut initialization code for brevity)
TileViewController *tile = [[TileViewController alloc] init];
// Figure out if working on Retina enabled device
static CGFloat scale = -1.0;
if(scale < 0.0){
UIScreen *screen = [UIScreen mainScreen];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0) {
scale = [screen scale];
}else{
scale = 0.0;
}
}
if(scale>0.0){
UIGraphicsBeginImageContextWithOptions(tile.view.bounds.size, NO, scale);
}else{
UIGraphicsBeginImageContext(tile.view.bounds.size);
}
[tile.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(image);
NSString *savePath = <create save path here>;
// Snipped out the code that saves this path to the core data store =
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createFileAtPath:savePath
contents:imageData
attributes:nil];
从这一点来说,我使用的UIImage在的UIImageView,它被放置在屏幕上。第一次运行时,从内存中显示时,它看起来很棒。第二次左右,我从磁盘使用下面的代码拉动相同的图像:
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:article.tileImagePath]) {
UIImage *image = [UIImage imageWithContentsOfFile:article.tileImagePath];
// send image to UIImageView
}
的问题是,当不产生图像的时间,但是从文件中去掉,在UILabels文在视网膜显示器上显得非常模糊。我可以在模拟器中查看生成的图像,并在mac上的查找器中查看它们,它们看起来很脆,尺寸适当(2倍缩放)。
有没有额外的步骤,我应该在这里?
答
我在question找到了解决方案。您必须设置适当的rasterizationScale
您的CALayer的财产:
tile.layer.rasterizationScale = [[UIScreen mainScreen] scale];