Capturing UIScrollView off screen content
Hello friends! This is my first post and it will be about my experience of making screenshot of UIScrollView.
So I have searched a lot but found not really a lot of suggestions of how to make it. So I decided to try the combination of what I have found. And finally it works!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
UIImage* viewImage = nil; UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, scrollView.opaque, 0.0); { CGPoint savedContentOffset = scrollView.contentOffset; CGRect savedFrame = scrollView.frame; scrollView.contentOffset = CGPointZero; scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height); [scrollView.layer renderInContext: UIGraphicsGetCurrentContext()]; viewImage = UIGraphicsGetImageFromCurrentImageContext(); scrollView.contentOffset = savedContentOffset; scrollView.frame = savedFrame; } UIGraphicsEndImageContext(); |
To make it work, you need to switch from use of UIGraphicsBeginImageContext as it described in most samples of making screen capture to
UIGraphicsBeginImageContextWithOptions (more detailed look to documentation on this page). Pass 0.0 for scale (the third argument) and you'll get a context with a scale factor equal to that of the screen.
UIGraphicsBeginImageContext uses a fixed scale factor of 1.0, so you're actually getting exactly the same image on an iPhone 4 as on the other iOS devices. It'will not take content that is located off the screen, you will get a screen with white stripe on the top or bottom if the size of the content will be off the screen.
So, the main idea is to use UIGraphicsBeginImageContextWithOptions function, and it's available from iOS SDK 4.0.
Hope this sample will be helpful for you my friend!
September 22nd, 2012 - 00:39
Thank you so much for posting this. I had been struggling with this for a long time. In the image that is produced all the background is black. Any idea why that would be or how to change it?
October 19th, 2012 - 13:33
I apologise, but, in my opinion, you are not right.
I am assured. I can prove it. Write to me in PM, we will communicate.
April 25th, 2013 - 14:54
Thanks for posting.
The background is black because scrollview.background is not set!
Happy coding!