how to take a screenshot of the iPhone programmatically?

前端 未结 11 1839
谎友^
谎友^ 2020-11-28 08:01

Is it possible in objective C that we can take the screen shot of screen and stored this image in UIImage.

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 08:26

    In modern way:

    Obj-C

    @interface UIView (Snapshot)
    - (UIImage * _Nullable)snapshot;
    @end
    
    @implementation UIView (Snapshot)
    
    - (UIImage * _Nullable)snapshot {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, UIScreen.mainScreen.scale);
        [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
    }
    
    @end
    

    Swift

    extension UIView {
        func snapshot() -> UIImage? {
            UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
            drawHierarchy(in: bounds, afterScreenUpdates: true)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
       }
    }
    

提交回复
热议问题