我正在尝试获取另一个控制器在动画中使用的视图的快照。我正在使用以下代码,但是除了该视图的背景颜色外,我什么也看不到,其子视图(两个按钮,一个文本视图和标签)都没有:
- (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,image以及所有内容都正确记录。
编辑后:如果我切换到当前控制器的视图,则可以正常工作,因此我认为这与获取不在屏幕上的视图的快照有关。可以做吗?
希望这对您有帮助:
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;
UIGraphicsBeginImageContextWithOptions(fpController.view.bounds.size, NO, 0.0);
UIGraphicsBeginImageContextWithOptions(destinationSize, NO, 0.0);
使用这两行代替UIGraphicsBeginImageContext(fpController.view.bounds.size);
UIGraphicsBeginImageContext(destinationSize); respectively
希望对您有帮助
我找到了一种使这项工作的方法,尽管它似乎是一个黑客。我添加了要渲染的视图作为视图的子视图,执行渲染,然后删除视图。从来没有在屏幕上看到它,所以从视觉上看很好。我只是想知道是否有更好的方法。
- (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];
}