how to get CoreAnimation frames

41 Views Asked by At

I want to generate video/gif with a animating UIView. This is the way i used CADisplayLink to capture UIView:

public func startCapture(fps: NSInteger){
    if let _ = captureDisplayLink {
        invlidateCaptureDispalyLink()
    }
    captureImages = []
    captureDisplayLink = CADisplayLink(target: self, selector: #selector(captureImageOnce))
    captureDisplayLink?.preferredFramesPerSecond = fps
    captureDisplayLink?.add(to: RunLoop.current, forMode: .common)
}

and this is the method to capture UIView into UIImage:

public func captureImage() -> UIImage?{
    var image: UIImage?
    UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, UIScreen.main.scale)
    if let context = UIGraphicsGetCurrentContext() {
        // context.concatenate(layer.affineTransform())
        drawHierarchy(in: bounds, afterScreenUpdates: true)
        image = UIGraphicsGetImageFromCurrentImageContext()
        context.restoreGState()
    }
    UIGraphicsEndImageContext()
    return image
}

finally, i get an image array, but every image seems same with others.

what's the right way to do this ?


I get frames using layer.presentation()?.render(in: context) . and then, an other promblem appears:

CoreAnimation is not supported,

/* Renders the receiver and its sublayers into 'ctx'. This method
     * renders directly from the layer tree. Renders in the coordinate space
     * of the layer.
     *
     * WARNING: currently this method does not implement the full
     * CoreAnimation composition model, use with caution. */
    
    /** Rendering properties and methods. **/
    open func render(in ctx: CGContext)

any ideal ?

1

There are 1 best solutions below

0
quanhai On

Use presentation() done.

public func captureImage() -> UIImage?{
        var image: UIImage?
        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, UIScreen.main.scale)
        if let context = UIGraphicsGetCurrentContext() {
            layer.presentation()?.render(in: context)
            image = UIGraphicsGetImageFromCurrentImageContext()
            context.restoreGState()
        }
        UIGraphicsEndImageContext()
        return image
    }