iOS 截屏
第一种
//截屏
- (UIImage *)ScreenCapture {
//创建一个context
//size画布的大小
//opaque是否有透明度
//scale画布的比率.
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
//把当前的全部画面导入到栈顶context中并进行渲染
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
//从当前context中创建一个新图片
UIImage * tempImage = UIGraphicsGetImageFromCurrentImageContext();
//是当前的context出堆栈
UIGraphicsEndImageContext();
return tempImage;
}
第二种
//截取任意位置,保存到相册
- (void)SaveScreenCaptureToPhoneAlbum {
UIGraphicsBeginImageContextWithOptions(self.view.frame.size, NO, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * tempImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsGetCurrentContext();
CGImageRef tempRef = tempImage.CGImage;
//截图区域
CGRect tempRect = CGRectMake(2*self.view.frame.origin.x, 2*self.view.frame.origin.y - 15, 2 * self.view.frame.size.width, 2 * self.view.frame.size.height);
CGImageRef tempImageRef = CGImageCreateWithImageInRect(tempRef, tempRect);
UIImage * sendImage = [[UIImage alloc] initWithCGImage:tempImageRef];
//保存到相册
UIImageWriteToSavedPhotosAlbum(sendImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
//保存到相册
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (error == nil) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已存入手机相册" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
[alert show];
}else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"保存失败,你的设置里的隐私设置,可能拒绝了,XXXXX访问你的照片" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
[alert show];
}
}