[英]How to take a screenshot programmatically in iOS?
我有一个使用UIKit
控件和OpenGL
的UIView
。 我想以编程方式获取该视图的屏幕截图。
如果我使用UIGraphicsGetImageFromCurrentImageContext()
,则OpenGL
内容为空; 如果我使用glReadPixels(...)
方法,则UIKit内容为空;
我很困惑如何拍摄完整的截图。 谢谢!
使用以下代码进行屏幕截图
-(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;
}
-(UIImage *) screenshot
{
CGImageRef UIGetScreenImage(void);
CGImageRef screen = UIGetScreenImage();
UIImage* screenImage = [UIImage imageWithCGImage:screen];
CGImageRelease(screen); // you need to call this.
return screenImage;
}
好吧,有几种方法可以通过编程方式捕获iPhone屏幕
使用UIKIT http://developer.apple.com/library/ios/#qa/qa1703/_index.html
使用AVFoundation框架http://developer.apple.com/library/ios/#qa/qa1702/_index.html
使用OpenGL ES http://developer.apple.com/library/ios/#qa/qa1704/_index.html
从iOS 7开始,你也可以使用为什么我在iOS 7上以编程方式创建的截图看起来如此糟糕?
使用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();
使用UIView
UIGraphicsBeginImageContext(self.view.frame.size); [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *viImage=UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
在这6个选项中,我发现第一个选项非常便于复制粘贴和应用压缩级别,因为第一种方法为图像提供了真实的像素数据。 我也喜欢选项4,因为API附带了SDK。
你得到的结果Uiimage没有失去图像质量
- (UIImage *)captureView:(UIView *)view {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data = [UIImagePNGRepresentation(image) retain];
UImage *screenShot = [UIImage imageWithData:data];
以下是如何以编程方式对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);
您知道OpenGL内容在视图中的位置。 因此,将glReadPixels
的结果复制到UIKit的快照中应该很容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.