有的app中會需要有一個截屏的小功能,下面看看代碼怎麼寫
給UIImage添加一個類目,寫一個截屏的方法
/**
控件截屏
@param view 傳入的View
@return 截屏圖片
*/
+ (UIImage *)imageWithCaputureView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[view.layer renderInContext:ctx];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
然後在控制器裏直接調用這個方法就行了,比如把截屏的圖片寫到桌面上
UIImage * imageNew = [UIImage imageWithCaputureView:self.view];
NSData * data = UIImageJPEGRepresentation(imageNew, 1);
[data writeToFile:@"/Users/mac/Desktop/image.png" atomically:YES];