iOS Developer小知识点好东西

代码实现截屏效果

2017-04-01  本文已影响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);
上一篇下一篇

猜你喜欢

热点阅读