iOS截圖-截取指定區(qū)域視圖

最近遇到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("保存成功")
        }
    }
  • 截取指定區(qū)域視圖
//傳入需要截取的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();
}
  • 截取指定區(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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容