I have a large image in terms of dimensions that go beyond the device's screen width.
I have loaded that large image into a scrollview on my app.
I have a button which triggers a manual scroll on the scrollview from one end to the other over a 10s period.
I want to convert this animation into a video and my purpose of posting this question is to find out the best / efficient / optimal way to do that.
I found this answer where he Zoul gives some ideas on how to convert an array of images into a video.
So here is what I tried:
I scrolled the scrollview from end to end over a 10s interval and I tried to take a screenshot of the view every 1/60th of a second, thinking I would get a 60 fps video doing this
func didTapPlayButton(_ sender: UIButton) {
UIView.animate(withDuration: 10.0, delay: 0.0, options: .curveEaseInOut) { [weak self] in
self?.startTakingScreenshots()
self?.scrollView.scrollToEnd(animated: false) // Custom UIScrollview extension function
} completion: { [weak self] (finished) in
self?.timer.invalidate()
self?.timer = nil
self?.generateMovie()
}
}
func startTakingScreenshots() {
timer = Timer.scheduledTimer(timeInterval: 1.0/60.0,
target:self ,
selector: #selector(snapScreenshot),
userInfo: nil,
repeats: true)
}
@objc func snapScreenshot() {
imageArray.append(imageView.takeScreenshot())
}
This is the code I use to take the screenshot which is an extension of UIImageView
extension UIImageView {
func takeScreenshot() -> UIImage {
// Begin context
UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.main.scale)
// Draw view in that context
drawHierarchy(in: self.bounds, afterScreenUpdates: true)
// And finally, get image
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if (image != nil) {
return image!
}
return UIImage()
}
I can confirm taking the screenshot works fine but here are the issues I am having:
After running for about 3-4 s, the app crashes and Xcode says it is due to memory pressure. I am guessing it is because holding such a large number of UIImages in an array is not a good idea ?
If I change the frame rate from 1/60s to 1/30s, the app does not crash and I reach the end with 505 frames saved to the array. I am still a bit confused about the math here. If I take 30 screenshots every second for 10 seconds, I was expecting 300 frames or am I getting this wrong ?
Is there a better / efficient / optimal way to convert a UIImage which pans on a scrollview into a video than what I have done above ? I saw some suggestions about screen recording but I do not want to record the whole screen and I am interested in recording the animation for a specific view
Could there be a solution to convert the UIImage directly into a video without needing the scrollview ?
Any ideas and suggestions would be highly appreciated.
Thanks in advance.