截图保存到文件中和本地相册

2015-11-20  本文已影响41人  小黄人写代码

以下方法都在同一.m文件中

- (IBAction)buttonAction:(UIButton *)sender
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 1.捕捉
        UIImage *newImage = [self captureWithView:self.view];
        
        // 2.写文件
        NSData *data = UIImagePNGRepresentation(newImage);
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"myTest.png"];
        [data writeToFile:path atomically:YES];
        
        // 3.写入到本地相册中
        UIImageWriteToSavedPhotosAlbum(newImage, self, nil, nil);
    });
}
/**
 *  截图
 *
 *  @param view 当前的view
 *
 *  @return UIImage
 */
- (UIImage *)captureWithView:(UIView *)view
{
    // 1.开启上下文
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0);
    
    // 2.将控制器view的layer渲染到上下文
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    // 3.取出图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 4.结束上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}
上一篇下一篇

猜你喜欢

热点阅读