如何在iOS中以编程方式截取屏幕截图?

coo*_*di8 9 iphone screenshot opengl-es uikit ios

我有一个UIView使用UIKit控制和OpenGL.我想以编程方式获取该视图的屏幕截图.

如果我使用UIGraphicsGetImageFromCurrentImageContext(),OpenGL内容是空白的; 如果我使用该glReadPixels(...)方法,则UIKit内容为空;

我很困惑如何拍摄完整的截图.谢谢!

Him*_*jan 8

使用以下代码进行屏幕截图

    -(UIImage *) screenshot
     {

          CGRect rect;
          rect=CGRectMake(0, 0, 320, 480);
          UIGraphicsBeginImageContext(rect.size);

          CGContextRef context=UIGraphicsGetCurrentContext();
          [self.view.layer renderInContext:context];

          UIImage *image=UIGraphicsGetImageFromCurrentImageContext();
          UIGraphicsEndImageContext();

          return image;
     }
Run Code Online (Sandbox Code Playgroud)


Tri*_*ent 5

好吧,以编程方式捕获 iPhone 屏幕的方法很少

  1. 使用 UIKIT http://developer.apple.com/library/ios/#qa/qa1703/_index.html

  2. 使用 AVFoundation 框架http://developer.apple.com/library/ios/#qa/qa1702/_index.html

  3. 使用 OpenGL ES http://developer.apple.com/library/ios/#qa/qa1704/_index.html

  4. 从 iOS 7 开始,您还可以使用为什么我以编程方式创建的屏幕截图在 iOS 7 上看起来如此糟糕?

  5. 使用 UIWindow

    CGRect screenRect = [[UIScreen mainScreen] bounds];
    UIGraphicsBeginImageContext(screenRect.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [[UIColor blackColor] set];
    CGContextFillRect(ctx, screenRect);
    [self.window.layer renderInContext:ctx];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    Run Code Online (Sandbox Code Playgroud)
  6. 使用 UIView

    UIGraphicsBeginImageContext(self.view.frame.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viImage=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    Run Code Online (Sandbox Code Playgroud)

在这 6 个选项中,我发现第一个选项对于复制粘贴和应用压缩级别非常方便,因为第一种方法为图像提供了真实的像素数据。我也喜欢选项 4,因为 API 随 SDK 一起提供。


Man*_*ann 5

-(UIImage *) screenshot
{
CGImageRef UIGetScreenImage(void);
CGImageRef screen = UIGetScreenImage();
UIImage* screenImage = [UIImage imageWithCGImage:screen];
CGImageRelease(screen); // you need to call this.
return screenImage;
}
Run Code Online (Sandbox Code Playgroud)


Iro*_*ill 0

以下是如何以编程方式截取UIImage. 如果您想要将其替换为任何其他对象,请将其替换UIImage为。

.h文件中添加, NSData *Data;然后在您的.m文件中将其添加到您的代码中

UIGraphicsBeginImageContext(self.view.frame.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *attachimage = [[UIImage alloc]initWithData:Data];
UIImage *viImage=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
attachimage = viImage;
UIImageWriteToSavedPhotosAlbum(viImage, nil, nil, nil);
Run Code Online (Sandbox Code Playgroud)