1

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

- (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、图像,所有的记录都正确。

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

4

3 回答 3

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;
于 2012-12-21T05:34:10.410 回答
1
UIGraphicsBeginImageContextWithOptions(fpController.view.bounds.size, NO, 0.0);


UIGraphicsBeginImageContextWithOptions(destinationSize, NO, 0.0);

使用这两行代替UIGraphicsBeginImageContext(fpController.view.bounds.size);

 UIGraphicsBeginImageContext(destinationSize); respectively 

希望对你有帮助

于 2012-12-21T05:27:08.287 回答
0

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

- (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];
}
于 2012-12-21T07:05:23.770 回答