4

我想将 UIView 转换为 UIImage

- (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;
}

两个问题:

  1. 我对我的观点有子观点。有没有办法在没有任何子视图的情况下创建视图图像?理想情况下,我希望不必删除它们只是为了稍后再添加它们。

  2. 此外,它无法在视网膜设备上正确渲染图像。我按照此处的建议将上下文与选项一起使用,但没有帮助。如何在不损失视网膜显示质量的情况下将 UIView 捕获到 UIImage

4

2 回答 2

2

您必须隐藏不想出现在视图图像中的子视图。下面也是为 Retina 设备渲染视图图像的方法。

- (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;
}
于 2013-09-05T06:59:58.803 回答
0
- (CGImageRef)toImageRef
{
    int width = self.frame.size.width;
    int height = self.frame.size.height;
    CGContextRef ref = CGBitmapContextCreate(NULL, width, height, 8, width*4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipLast);
    [self drawRect:CGRectMake(0.0, 0.0, width, height) withContext:ref];
    CGImageRef result = CGBitmapContextCreateImage(ref);
    CGContextRelease(ref);
    return result;
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    // move your drawing commands from here...
    [self drawRect:rect withContext:context];
}

- (void)drawRect:(CGRect)rect withContext:(CGContextRef)context
{
    // ...to here
}
于 2014-01-17T13:56:58.120 回答