最近遇到iOS截屏需求,有全屏截取和部分截取。今天帮大家整理一下
Swift
- 截取全屏
func screenShot() {
//截屏
let screenRect = UIScreen.mainScreen().bounds
UIGraphicsBeginImageContext(screenRect.size)
let ctx:CGContextRef = UIGraphicsGetCurrentContext()!
self.view.layer.renderInContext(ctx)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
//保存相册,可以去相册验证截图是否是你想要的
UIImageWriteToSavedPhotosAlbum(ima!, self, #selector(ViewController.image(_:didFinishSavingWithError:contextInfo:)), nil)
}
func image(image:UIImage,didFinishSavingWithError error:NSError?,contextInfo:AnyObject) {
if error != nil {
print("保存失败")
} else {
print("保存成功")
}
}
- 截取指定区域视图
//传入需要截取的view
func screenShotView(view: UIView) -> UIImage {
let imageRet : UIImage
UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0.0)
view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
imageRet = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
//保存相册,可以去相册验证截图是否是你想要的 (方法同上)
UIImageWriteToSavedPhotosAlbum(ima!, self, #selector(ViewController.image(_:didFinishSavingWithError:contextInfo:)), nil)
return imageRet
}
Objective-C
- 截取全屏
-(void)screenShot{
CGRect screenRect = [UIScreen mainScreen].bounds;
UIGraphicsBeginImageContext(screenRect.size);
UIGraphicsGetCurrentContext();
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); //image就是截取的图片
UIGraphicsEndImageContext();
}
- 截取指定区域视图
//传入需要截取的view
-(UIImage *)screenShotView:(UIView *)view{
UIImage *imageRet = [[UIImage alloc]init];
UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
imageRet = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return imageRet;
}