標籤:style class code ext color com
一. IOS 的截取全屏代碼為:
UIWindow *screenWindow = [[UIApplication sharedApplication] keyWindow]; //1.截屏 UIGraphicsBeginImageContext(screenWindow.frame.size); [screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
二. 截取指定地區:
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,self.view.opaque,0.0);
[self.myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage*theImage=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData*theImageData=UIImageJPEGRepresentation(theImage,1.0 );//you can use PNG too
[theImageData writeToFile:@"example.jpeg" atomically:YES];
三.截屏代碼的單例
ScreenShot.h檔案
#import <Foundation/Foundation.h>@interface ScreenShot : NSObject///截屏圖片存放位置@property (nonatomic,copy) NSString *filePath;/* 單例函數 */+ (id)sharedScreenShot;/* 截屏,並寫入記憶體 */-(void)getScreenImage;@end
ScreenShot.m檔案
#import "ScreenShot.h"///截屏圖片#define ScreenShotImage @"screenshot.png"@implementation ScreenShot@synthesize filePath=_filePath;- (id)init { if (self = [super init]) { _filePath=[self documentsPathForFileName:ScreenShotImage]; } return self;}#pragma mark -單例+ (id)sharedScreenShot { static ScreenShot *screenShot = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ screenShot = [[self alloc] init]; }); return screenShot;}#pragma mark 通過檔案名稱獲得路徑- (NSString *)documentsPathForFileName:(NSString *)name{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); NSString *documentsPath = [paths objectAtIndex:0]; return [documentsPath stringByAppendingPathComponent:name];}#pragma mark - 截屏-(void)getScreenImage{ UIWindow *screenWindow = [[UIApplication sharedApplication] keyWindow]; //1.截屏 UIGraphicsBeginImageContext(screenWindow.frame.size); [screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); //2.儲存 NSData *screenshotPNG = UIImagePNGRepresentation(screenshot); NSError *error = nil; //3.寫入記憶體 [screenshotPNG writeToFile:_filePath options:NSAtomicWrite error:&error];}@end
四.使用:
1.在ViewController中引入標頭檔ScreenShot.h
//截屏並儲存 [ScreenShot sharedScreenShot] getScreenImage];
2. 獲得圖片
NSString *shotFilePath=((ScreenShot *)[ScreenShot sharedScreenShot]).filePath; NSData *shotImageData = [NSData dataWithContentsOfFile:shotFilePath]; UIImage *shotImage = [UIImage imageWithData:shotImageData];