视图快照不渲染

时间:2012-12-21 05:14:09

标签: ios uiimage

我正在尝试获取另一个控制器视图的快照,以便在动画中使用。我正在使用以下代码,但我只看到该视图的背景颜色,并且没有任何子视图(两个按钮,一个文本视图和一个标签):

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    FirstPageController *fpController = [self.storyboard instantiateViewControllerWithIdentifier:@"FirstPage"];
    UIGraphicsBeginImageContext(fpController.view.bounds.size);
    NSLog(@"%@",fpController.view.subviews);
    [fpController.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGSize destinationSize = CGSizeMake(90, 122);

    UIGraphicsBeginImageContext(destinationSize);
    [viewImage drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    self.imageView2 = [[UIImageView alloc] initWithImage:newImage];
    self.imageView2.center = self.view.center;
    [self.view addSubview:self.imageView2];
     NSLog(@"%@",NSStringFromCGSize(self.imageView2.image.size));
}

我已经记录了所有相关内容,fpController,imageView,图像以及所有正确记录的内容。

编辑后:如果我切换到当前控制器的视图,它工作正常,所以我认为这与获取不在屏幕上的视图的快照有关。可以这样做吗?

3 个答案:

答案 0 :(得分:3)

希望这会对你有所帮助:

 CGSize textcontent =CGSizeMake(width, height);
UIGraphicsBeginImageContext(textcontent);
if ([UIScreen instancesRespondToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2.0f)
{
    UIGraphicsBeginImageContextWithOptions(textcontent, YES, 1.0f);
}
else
{
    UIGraphicsBeginImageContext(textcontent);
}
    [image.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return viewImage;

答案 1 :(得分:1)

UIGraphicsBeginImageContextWithOptions(fpController.view.bounds.size, NO, 0.0);


UIGraphicsBeginImageContextWithOptions(destinationSize, NO, 0.0);

使用这两行而不是UIGraphicsBeginImageContext(fpController.view.bounds.size);

 UIGraphicsBeginImageContext(destinationSize); respectively 

希望对你有所帮助

答案 2 :(得分:0)

我找到了一种方法来完成这项工作,尽管它似乎是一种黑客攻击。我将要渲染的视图添加为视图的子视图,执行渲染,然后删除视图。从来没有在屏幕上看到它,所以在视觉上,这很好。我只是想知道是否有更好的方法。

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.fpController = [self.storyboard instantiateViewControllerWithIdentifier:@"FirstPage"];

    [self.view insertSubview:self.fpController.view belowSubview:self.view];

    UIGraphicsBeginImageContext(self.fpController.view.bounds.size);
    [self.fpController.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [self.fpController.view removeFromSuperview];

    self.imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 90, 122)];
    self.imageView2.image = viewImage;
    [self.pageView insertSubview:self.imageView2 belowSubview:self.imageView];
}