最近工作维护老项目的时候发现一个问题,图片失真模糊不清,因为是老项目好多地方不太方法不太明白,定位问题可能由于
UIGraphicsBeginImageContext
或者
UIGraphicsGetImageFromCurrentImageContext
引起,所以各种dash、Google 最后找到解决办法:全文复制
问题解决办法如下
最近工作中,遇到一个需求,需要把一个UIView对象转成UIImage对象显示。经过网络搜索,找到如下答案:
-(UIImage*)convertViewToImage:(UIView*)v{
CGSize s = v.bounds.size;
UIGraphicsBeginImageContext(s);
[v.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
运行后发现,需求基本达到,但是有个问题,转换后的UIImage显示后会变模糊。因此猜测,这个方法适用于iPhone4之前的机型。iPhone4后,由于采用了Retain高清屏,在转换时需要根据屏幕密度做个处理,又到到下面的答案:
-(UIImage*)convertViewToImage:(UIView*)v{
CGSize s = v.bounds.size;
UIGraphicsBeginImageContextWithOptions(s, NO, v.layer.contentsScale);
[v.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
运行后,问题依旧。于是跟踪了一下contentsScale的值,发现也是1.0。这里我也不太清楚原因,本来是运行在Retain屏的设备上,为什么不是2.0。
只好自己修改成下面的样子:
-(UIImage*)convertViewToImage:(UIView*)v{
CGSize s = v.bounds.size;
// 下面方法,第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果,需要传NO,否则传YES。第三个参数就是屏幕密度了
UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
[v.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
变模糊和失真的问题解决了。
原文链接:cocoachina