UIGraphicsGetCurrentContext和UIScrollView [英] UIGraphicsGetCurrentContext and UIScrollView

查看:100
本文介绍了UIGraphicsGetCurrentContext和UIScrollView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将UIScrollView的所有内容保存到.pdf。我找到了一些用于保存当前视图的教程,它们都依赖于使用 UIGraphicsGetCurrentContext()创建CGContextRef。现在,我只是用

I'm trying to save all of the contents of a UIScrollView to a .pdf. I found some tutorials for saving the current view, and they all rely on creating a CGContextRef using UIGraphicsGetCurrentContext(). Right now, I capture my view with just

CGContextRef context = UIGraphicsGetCurrentContext();
[myView.layer renderInContext:context];

对于普通的UIView来说效果很好。但是,当我尝试将UIScrollView传递为 myView 时,它可以很好地传递UIScrollView的可见部分,但是屏幕外的所有内容都是空白。 是否可以通过某种方式扩展上下文来获取UIScrollView中的所有内容,而不仅仅是当前可见的内容?我怀疑我不能将 UIGraphicsGetCurrentContext()用于UIScrollView,但是我不知道该用什么,而 Apple文档对此并不是很有帮助。

And that works fine for a plain UIView. However, when I try to pass a UIScrollView as myView, it passes the visible part of the UIScrollView fine, but anything offscreen is just white space. Is there a way I can expand context somehow to get all of the content in my UIScrollView, and not just what is currently visible? I suspect that I can't use UIGraphicsGetCurrentContext() for a UIScrollView, but I don't know what to use instead, and the Apple docs on this aren't really very helpful.

推荐答案

如果您有一个子视图,它使用了带有滚动内容的scrollView的整个内容大小,则可以这样:

If you have a subview taking the whole content size of the scrollView with the scrolling content you can do it like this:

CGContextRef context = UIGraphicsGetCurrentContext();
UIView *contentView = [scrollView subviews][0];
[contentView.layer renderInContext:context];

如果scrollView中有多个视图,您可以这样:

If there are multiple views in the scrollView you can do it like this:

UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(
                                                          scrollView.frame.origin.x,
                                                          scrollView.frame.origin.y, 
                                                          scrollView.contentSize.width, 
                                                          scrollView.contentSize.height)];
for(UIView *view in [scrollView subviews]){
 [contentView addSubview: view];
}

CGContextRef context = UIGraphicsGetCurrentContext();
[contentView.layer renderInContext:context];

然后,您需要将视图返回到scrollView中。也许有一种方法可以复制它们,但我不确定如何复制。无论如何,这里应该起作用:

Then you need to get the views back into the scrollView. Probably there is a way to copy them but I am not sure how. Anyhow here is what should work:

for(UIView *view in [contentView subviews]){
 [view removeFromSuperView];
 [scrollView addSubview:view];
}

这篇关于UIGraphicsGetCurrentContext和UIScrollView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆