图片处理

iOS截图-截取指定区域视图

2016-12-17  本文已影响5154人  R_yan

最近遇到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;
}
上一篇 下一篇

猜你喜欢

热点阅读