iOS基础(十七)——根据一个View生成一个image

根据一个View生成一个image

+ (UIImage *)screenshotForView:(UIView *)view {
    UIImage *image = nil;
    //判断View类型(一般不是滚动视图或者其子类的话内容不会超过一屏,当然如果超过了也可以通过修改frame来实现绘制)
    if ([view.class isSubclassOfClass:[UIScrollView class]]) {
        UIScrollView *scrView = (UIScrollView *)view;
        
        CGPoint tempContentOffset = scrView.contentOffset;
        CGRect tempFrame = scrView.frame;
        
        scrView.contentOffset = CGPointZero;
        scrView.frame = CGRectMake(0, 0, scrView.contentSize.width, scrView.contentSize.height);
        
        image = [self screenshotForView:scrView size:scrView.frame.size];
        
        scrView.contentOffset = tempContentOffset;
        scrView.frame = tempFrame;
        
    } else {
        image = [self screenshotForView:view size:view.frame.size];
    }
    
    return image;
}
+ (UIImage *)screenshotForView:(UIView *)view size:(CGSize)size {
    UIImage *image = nil;
    UIGraphicsBeginImageContextWithOptions(size, YES, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    return image;
}
posted @ 2018-09-18 18:04  明似水  阅读(346)  评论(0编辑  收藏  举报