Search code examples
iosswiftcore-graphicsscreenshotarkit

Unable to take screenshot - screen size and return image issue


I have screen equal the size of the SceneView im looking to capture

let screen = CGRect(x: 0, y: 0, width: sceneView.frame.size.width, height: sceneView.frame.size.height - 60)


Regarding the size, I am greeted with a "cannot invoke initializer for type CGFloat with an argument list of type (CGRect). How would I go about fixing this error?

func Screenshot()
{
        UIGraphicsBeginImageContextWithOptions(UIScreen.main.bounds.size, false, CGFloat(screen))
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
}

Solution

  • You have passed wrong parameter type an argument to UIGraphicsBeginImageContextWithOptions. Last argument is of type CGFloat, that accepts float value but you've passed value of type CGRect (screen).

    UIGraphicsBeginImageContextWithOptions has following parameters arguments

    void UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale)
    


    Parameters

    size
    The size (measured in points) of the new bitmap context. This represents the size of the image returned by the UIGraphicsGetImageFromCurrentImageContext function. To get the size of the bitmap in pixels, you must multiply the width and height values by the value in the scale parameter.

    opaque
    A Boolean flag indicating whether the bitmap is opaque. If you know the bitmap is fully opaque, specify YES to ignore the alpha channel and optimize the bitmap’s storage. Specifying NO means that the bitmap must include an alpha channel to handle any partially transparent pixels.

    scale
    The scale factor to apply to the bitmap. If you specify a value of 0.0, the scale factor is set to the scale factor of the device’s main screen.

    Here Apple's Document for this function: UIGraphicsBeginImageContextWithOptions

    Solution (hint): Pass value 0.0 or 1.0 instead of screen and see.

    UIGraphicsBeginImageContextWithOptions(UIScreen.main.bounds.size, false, CGFloat(1.0))