iOS开发之获取view的截图

一、获取普通视图的截图

#pragma mark 获取截屏图片
- (UIImage *)captureScreenForView:(UIView *)currentView {
    // 开启一个绘图的上下文
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(currentView.size.width, currentView.size.height), NO, 0.0);
    // 作用于CALayer层的方法。将view的layer渲染到当前的绘制的上下文中。
    [shotView drawViewHierarchyInRect:CGRectMake(0, 0, currentView.frame.size.width, currentView.frame.size.height) afterScreenUpdates:YES];
    // 获取图片
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束绘图上下文
    UIGraphicsEndImageContext();
    
    return  viewImage;
}

二、获取滚动视图的内容截图

+ (UIImage *)screenShotWithView:(UIScrollView *)shotView shotSize:(CGSize)shotSize {
    // 开启图片上下文
    UIGraphicsBeginImageContextWithOptions(shotSize, NO, 0.f);
    
    // 保存现在视图的位置偏移信息
    CGPoint saveContentOffset = shotView.contentOffset;
    
    // 保存现在视图的frame信息
    CGRect saveFrame = shotView.frame;
    // 把要截图的视图偏移量设置为0
    shotView.contentOffset = CGPointZero;
    // 设置要截图的视图的frame为内容尺寸大小
    shotView.frame = CGRectMake(0, 0, shotSize.width, shotSize.height);
    
    // 截图:实际是把layer上面的东西绘制到上下文中
    [shotView drawViewHierarchyInRect:CGRectMake(0, 0, shotSize.width, shotSize.height) afterScreenUpdates:YES];
    // 获取截图
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    // 关闭图片上下文
    UIGraphicsEndImageContext();
    // 将视图的偏移量设置回原来的状态
    shotView.contentOffset = saveContentOffset;
    // 将视图的frame信息设置回原来的状态
    shotView.frame = saveFrame;
    
    return image;
}

猜你喜欢

转载自blog.csdn.net/guoxulieying/article/details/117459916#comments_16846118
今日推荐