IOS屏幕截图---普通截图

应煌
2023-12-01

============================================================
博文原创,转载请声明出处
电子咖啡(原id蓝岩)
============================================================
分享一段屏幕截图的代码,能够截图普通的button,image,等。

对于截取摄像头的图像,比较复杂,因为摄像头是通过opengl渲染到view上面的,通过下面的代码并不能截取。

就像我们远程登录了另一台windows电脑时候,能看到对方的桌面等,但对方的视频我们并不能看到。

关于截取opengl view的方法,我会在另一篇博客中记录: 

IOS屏幕截图---Opengl截屏

我已经在我的工程中测试过,可以使用



//普通屏幕截取

首先引入头:

#include <QuartzCore/QuartzCore.h>


/**
@view  the view you want to take screen shot
*/
-(UIImage*)getNormalImage:(UIView*)view{
    UIGraphicsBeginImageContext(CGSizeMake(320,480));
    CGContextRef context = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:context];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


//将UIIamge存储到相册中

//store the image to the iphone photo album
UIImage *image =nil;
// init your image
UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);


//存储UIImage到本地磁盘,包括png和jpeg格式

//store the image to the app Document
-(void)saveToDisk:(UIImage*) image{
    
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
	// If you go to the folder below, you will find those pictures
	NSLog(@"%@",docDir);
    
	NSLog(@"saving png");
	NSString *pngFilePath = [NSString stringWithFormat:@"%@/test%f.png",docDir,[NSDate timeIntervalSinceReferenceDate]];
	NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
	[data1 writeToFile:pngFilePath atomically:YES];
    
	NSLog(@"saving jpeg");
	NSString *jpegFilePath = [NSString stringWithFormat:@"%@/test%f.jpeg",docDir,[NSDate timeIntervalSinceReferenceDate]];
	NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
	[data2 writeToFile:jpegFilePath atomically:YES];
    
	NSLog(@"saving image done");

}


ref:

Download an Image and Save it as PNG or JPEG in iPhone SDK ‹ ObjectGraph Blog

iphone - Why do I get 'No -renderInContext: method found' warning? - Stack Overflow

iphone - Programmatically take a screenshot combining OpenGL and UIKit elements - Stack Overflow

iPhone – saving OpenGL ES content to the Photo Album | BIT-101

opengl es - Why is glReadPixels() failing in this code in iOS 6.0? - Stack Overflow



 类似资料: