截屏方法有很多中糯笙,這里只寫一種最簡(jiǎn)單的永票,以及什么樣的情況下用什么參數(shù)
具體的主要函數(shù)如下:
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, YES, 0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
第一個(gè)函數(shù):
UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale)
size 畫(huà)布的大小
opaque 是否有透明度
scale 畫(huà)布的比率,這個(gè)參數(shù)關(guān)系到當(dāng)前所截圖片的清晰度一般設(shè)置為當(dāng)前屏幕的比率 [UIScreen mainScreen].scale
如果不關(guān)心這些秃嗜,也可以直接使用
UIGraphicsBeginImageContext(self.view.bounds.size)
但涉及到分享的時(shí)候最好使用options函數(shù)储玫;
封裝了一下,具體寫法:
+ (UIImage*)mcScreenShotWithObject:(id)target
shotSize:(CGSize)size
isOpaque:(BOOL)opaque
isSave:(BOOL)isSave
saveName:(NSString*)name{
UIGraphicsBeginImageContextWithOptions(size, opaque, [UIScreen mainScreen].scale);
if ([target isKindOfClass:[UIView class]]) {
UIView *view = (UIView*)target;
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
}else if ([target isKindOfClass:[UIViewController class]]){
UIViewController *viewController = (UIViewController*)target;
[viewController.view.layer renderInContext:UIGraphicsGetCurrentContext()];
}else{
NSAssert([target isKindOfClass:[UIView class]] || [target isKindOfClass:[UIViewController class]], @"數(shù)據(jù)源有問(wèn)題驯镊,請(qǐng)檢查并更新!");
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if (isSave) {
NSString * filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"DocumentPath"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
[fileManager createFileAtPath:[filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@.png",(name && ![name isEqualToString:@""])?name:@"image"]] contents:UIImagePNGRepresentation(image) attributes:nil];
NSLog(@"====>>%@ Path:%@%@",(name && ![name isEqualToString:@""])?name:@"image", filePath,[NSString stringWithFormat:@"/%@.png",(name && ![name isEqualToString:@""])?name:@"image"]);
}
return image;
}