我想将UIView转换为UI
Image
- (UIImage *)renderToImage:(UIView *)view {
if(UIGraphicsBeginImageContextWithOptions != NULL) {
UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0);
} else {
UIGraphicsBeginImageContext(view.frame.size);
}
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
两个问题:
>我的观点有子视图.有没有办法在没有任何子视图的情况下创建视图图像?理想情况下,id不必删除它们只是为了稍后再添加它们.
>此外,它不能在视网膜设备上正确渲染图像.我按照这里的建议使用上下文和选项,但它没有帮助. How to capture UIView to UIImage without loss of quality on retina display
最佳答案 您必须隐藏您不希望在视图图像中的子视图.下面是为视网膜设备渲染视图图像的方法.
- (UIImage *)imageOfView:(UIView *)view
{
// This if-else clause used to check whether the device support retina display or not so that
// we can render image for both retina and non retina devices.
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
} else {
UIGraphicsBeginImageContext(view.bounds.size);
}
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}