Created
September 8, 2011 17:41
-
-
Save jdewind/1204051 to your computer and use it in GitHub Desktop.
Capture the entire contents of a UITableView or UIScrollView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static UIImage* CreateImageFromView(UITableView *view) | |
{ | |
UIGraphicsBeginImageContextWithOptions(CGSizeMake(view.contentSize.width, view.contentSize.height), NO, 0.0f); | |
CGContextRef context = UIGraphicsGetCurrentContext(); | |
CGRect previousFrame = view.frame; | |
view.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y, view.contentSize.width, view.contentSize.height); | |
[view.layer renderInContext:context]; | |
view.frame = previousFrame; | |
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); | |
UIGraphicsEndImageContext(); | |
return image; | |
} |
To swift 4.0
func createImage() -> UIImage{
UIGraphicsBeginImageContextWithOptions(CGSize(width: contentSize.width, height: contentSize.height), false, 0.0)
let context = UIGraphicsGetCurrentContext()
let previousFrame = frame
frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: contentSize.width, height: contentSize.height)
layer.render(in: context!)
frame = previousFrame
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image;
}
wonderful !!!
@aliamcami: If I use the given code it calculates table view's contentsize correctly but fails to load contents of tableview/scrollview.
Hey @iPhoneNoobDeveloper can you try this?
public extension UIScrollView {
public var snapshot: UIImage? {
UIGraphicsBeginImageContextWithOptions(contentSize, false, 0)
defer {
UIGraphicsEndImageContext()
}
guard let context = UIGraphicsGetCurrentContext() else { return nil }
let previousFrame = frame
frame = CGRect(origin: frame.origin, size: contentSize)
layer.render(in: context)
frame = previousFrame
return UIGraphicsGetImageFromCurrentImageContext()
}
}
Hi @aliamcami, I want to take a screenshot of the full content of tableview. I tried your code above but the rest of the content that doesn't fit on the screen if getting cut off. (In white in the bottom)
Do you know why? Tks
All content which is not rendered at bottom of table can not be captured. You just captured what was rendered in the screen.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have used your code in my app (I have tried uittextview and uitableview) and it works well with using short text. however when I am trying to put long text to create image it shows an odd behavior. for instance the size of image which we want to create is normally rendered but some part of it's text lost and left with empty white space. i am looking forward your kind help.