需求:把一个UIView对象转成UIImage并保存到相册
一开始尝试了如下方法:
1 2 3 4 5 6 7
|
- (UIImage *)createImageFromView:(UIView *)view { UIGraphicsBeginImageContext(CGSizeMake(view.bounds.size.width, view.bounds.size.height)); [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }
|
使用了之后,发现一个问题,图片模糊失真。
解决思路:现在iPhone设备基本都是Retain屏,我们可以根据屏幕密度做转换处理,完美解决这个问题。
1 2 3 4 5 6 7
|
- (UIImage *)createImageFromView:(UIView *)view { UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [UIScreen mainScreen].scale); [view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }
|
参考文档
- 如何把UIView转成UIImage,解决模糊失真问题
近期评论