iosswiftuiviewios-multithreading

How to take a screenshot of UIView on a background thread?


The app I'm working on has google maps on almost every screen. To save memory, I'm reusing the same google maps view everywhere. The problem is, when you pop a viewController, you can see a white space where the map was. To work around that I'm taking screenshots of it and adding as a background before removing the map. But there's another problem, taking a screenshot takes about 0.3 seconds on iPhoneX (I suppose it's even worse on older phones). Is there any way to take screenshots of UIView on a background thread?


Solution

  • Actually ,it is possible! But first on UIThread you need get some infos Like this:

    CALayer* layer = view.layer;
    CGRect frame = view.frame;
    

    , then change to backgroundthead use codes below to get image:

    UIGraphicsBeginImageContextWithOptions(frame.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [layer renderInContext:context];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();