Capturing full screenshot with status bar in iOS programmatically

后端 未结 7 2378
执笔经年
执笔经年 2020-12-14 03:45

I am using this code to capture a screenshot and to save it to the photo album.

-(void)TakeScreenshotAndSaveToPhotoAlbum
{
   UIWindow *window = [UIApplicati         


        
相关标签:
7条回答
  • Answer of above question for Objective-C is already write there, here is the Swift version answer of above question.

    For Swift 3+

    Take screenshot and then use it to display somewhere or to send over web.

    extension UIImage {
        class var screenShot: UIImage? {
            let imageSize = UIScreen.main.bounds.size as CGSize;
            UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
            guard let context = UIGraphicsGetCurrentContext() else {return nil}
            for obj : AnyObject in UIApplication.shared.windows {
                if let window = obj as? UIWindow {
                    if window.responds(to: #selector(getter: UIWindow.screen)) || window.screen == UIScreen.main {
                        // so we must first apply the layer's geometry to the graphics context
                        context.saveGState();
                        // Center the context around the window's anchor point
                        context.translateBy(x: window.center.x, y: window.center
                            .y);
                        // Apply the window's transform about the anchor point
                        context.concatenate(window.transform);
                        // Offset by the portion of the bounds left of and above the anchor point
                        context.translateBy(x: -window.bounds.size.width * window.layer.anchorPoint.x,
                                             y: -window.bounds.size.height * window.layer.anchorPoint.y);
    
                        // Render the layer hierarchy to the current context
                        window.layer.render(in: context)
    
                        // Restore the context
                        context.restoreGState();
                    }
                }
            }
            guard let image = UIGraphicsGetImageFromCurrentImageContext() else {return nil}
            return image
        }
    }
    

    Usage of above screenshot

    • Lets display above screen shot on UIImageView

      yourImageView = UIImage.screenShot
      
    • Get image Data to save/send over web

      if let img = UIImage.screenShot {
          if let data = UIImagePNGRepresentation(img) {
              //send this data over web or store it anywhere
          }
      }
      
    0 讨论(0)
提交回复
热议问题