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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值