iOS 对view进行截图

/ 0评 / 0

需要对WKWebView进行截图,之前用的是下面的方法,高版本的系统是没有问题的,低版本的却截到一张白图

- (UIImage *)convertViewToImage:(UIView *)view{
    // 第二个参数表示是否非透明。如果需要显示半透明效果,需传NO,否则YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(view.bounds.size.width, view.bounds.size.height * 0.8),YES,[UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

查看了之后发现是层级有问题,没有截到最上面的视图,于是改为下面的方法就行了

- (UIImage*)captureView:(UIView *)theView frame:(CGRect)frame{
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(theView.bounds.size.width, theView.bounds.size.height*0.8), YES, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIImage *img;
    if([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0){
        for(UIView *subview in theView.subviews){
            [subview drawViewHierarchyInRect:subview.bounds afterScreenUpdates:YES];
        }
        img = UIGraphicsGetImageFromCurrentImageContext();
    }else{
        CGContextSaveGState(context);
        [theView.layer renderInContext:context];
        img = UIGraphicsGetImageFromCurrentImageContext();
    }
    UIGraphicsEndImageContext();
    return img;
}

要注意,frame是不能为空的,而且截的太快的话也会有问题,需要设置afterScreenUpdates为NO,因为设置为YES后,这些方法会等在view update结束在执行,如果在update结束前view被release了,会出现找不到view的问题。另外记得使用UIGraphicsBeginImageContextWithOptions,这样截取出来的是高清图。

评论已关闭。