最近遇到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()
//保存相冊(cè),可以去相冊(cè)驗(yàn)證截圖是否是你想要的
UIImageWriteToSavedPhotosAlbum(ima!, self, #selector(ViewController.image(_:didFinishSavingWithError:contextInfo:)), nil)
}
func image(image:UIImage,didFinishSavingWithError error:NSError?,contextInfo:AnyObject) {
if error != nil {
print("保存失敗")
} else {
print("保存成功")
}
}
- 截取指定區(qū)域視圖
//傳入需要截取的view
func screenShotView(view: UIView) -> UIImage {
let imageRet : UIImage
UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0.0)
view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
imageRet = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
//保存相冊(cè),可以去相冊(cè)驗(yàn)證截圖是否是你想要的 (方法同上)
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();
}
- 截取指定區(qū)域視圖
//傳入需要截取的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;
}