IOS给任意UIView截屏

来源:互联网 发布:网络尖兵防御是什么 编辑:程序博客网 时间:2024/06/08 06:35
//获得某个window的某个subViewUIView *view = [[[[[UIApplication sharedApplication] windows] objectAtIndex:0] subviews] lastObject];NSInteger index = 0;//用来给保存的png命名for (UIView *subView in [view subviews]) {//遍历这个view的subViewsif ([subView isKindOfClass:NSClassFromString(@"MKMapView")]) {//找到自己需要的subViewNSLog(@"fund");//支持retina高分的关键if(UIGraphicsBeginImageContextWithOptions != NULL){UIGraphicsBeginImageContextWithOptions(subView.frame.size, NO, 0.0);} else {UIGraphicsBeginImageContext(subView.frame.size);}//获取图像[subView.layer renderInContext:UIGraphicsGetCurrentContext()];UIImage *image = UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();//保存图像NSString *path = [NSHomeDirectory() stringByAppendingFormat:@"/%d.png",index];if ([UIImagePNGRepresentation(image) writeToFile:path atomically:YES]) {index += 1;NSLog(@"Succeeded! %@",path);}else {NSLog(@"Failed!");}}}