代码实现截屏效果

作者: 少少少少少少少 | 来源:发表于2017-04-01 14:07 被阅读200次

    今天在玩别的直播软件时看到了一个截屏后分享的功能,参考网上的文章自己实现了一下效果,如下图是截屏后保存在相册的图片


    IMG_0043.PNG

    首先导入#import <QuartzCore/QuartzCore.h>
    添加一个按钮

    UIButton *ScreenButton = [[UIButton alloc]initWithFrame:CGRectMake(200, 500, 50,50 )];
        ScreenButton.backgroundColor = [UIColor blackColor];
        [ScreenButton addTarget:self action:@selector(Screenshot) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:ScreenButton];
    

    然后点击黑色按钮调用截屏功能

    #pragma mark - 截图功能
    - (void)Screenshot {
    
        if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]){
            UIGraphicsBeginImageContextWithOptions(self.view.window.bounds.size, NO, [UIScreen mainScreen].scale);
        } else {
            UIGraphicsBeginImageContext(self.view.window.bounds.size);
        }
        [self.view.window.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *ScreenImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    //存入相册,这里记得需要在info.plist写入访问权限
        UIImageWriteToSavedPhotosAlbum(ScreenImage, nil, nil, nil);
    }
    
    
    38DE99E6-40B3-4067-9748-DA5C31E32E59.png
    2018.4.9更新
    现在在做直播项目,然后用到了截图功能才发现上面的截图是不能直播视频的,要使用下面的
     UIWindow *mainWindow = [UIApplication sharedApplication].keyWindow;
        UIGraphicsBeginImageContextWithOptions(mainWindow.frame.size, NO, 0);
        [mainWindow drawViewHierarchyInRect:mainWindow.frame afterScreenUpdates:YES];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    

    相关文章

      网友评论

        本文标题:代码实现截屏效果

        本文链接:https://www.haomeiwen.com/subject/edyiottx.html