Karthik Shiva
Karthik Shiva

Reputation: 23

Convert contents of UICollectionView to an Image

I need convert the contents of an UICollectionView into an UIIImage. But, the image only contains the visible portion of the UICollectionView and leaves out the parts which are yet to be rendered. Is there any that I can achieve it ?

I am using the following extension

func toImage() -> UIImage {
    let renderer = UIGraphicsImageRenderer(size: self.bounds.size)
    return renderer.image { ctx in
        self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
    }
}

Upvotes: 1

Views: 442

Answers (2)

matt
matt

Reputation: 535191

Is there any that I can achieve it ?

No, at least not by a simple screen capture. The offscreen cells do not even exist, so there is nothing for you to capture.

Upvotes: 1

Giridhar
Giridhar

Reputation: 104

There are two reasons why your full Collection View is not rendered as an Image.

  1. You call drawHierarchy in self.bounds, which will only capture the content in the specified bounds
  2. The rest of the collection view will not be rendered as the rest of the cells will be off screen.

Upvotes: 0

Related Questions