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; | |
} |
thank you very much , it is very helpful to me .
thank you.
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.
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.
thank you!!!