文章

如何利用 UIScrollView 解决 UIView 长图片绘制失败的问题

最近在做一个分享需求的时候遇到了一个问题:将比较长的 UIView 绘制为 UIImage 的时候,会绘制失败,得到的是全黑/全白的图片

我们知道,将 UIView 绘制为 UIImage 的方法有以下几种:

  1. 使用 UIView 的系统方法

    1
    2
    3
    4
    5
    6
    7
    
     - (BOOL)drawViewHierarchyInRect:(CGRect)rect afterScreenUpdates:(BOOL)afterUpdates;
    
     // example
     UIGraphicsBeginImageContextWithOptions(mainView.bounds.size, mainView.opaque, 0.0f);
     [mainView drawViewHierarchyInRect:mainView.bounds afterScreenUpdates:YES];
     UIImage *snapShotImage = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();
    
  2. 使用 CALayer 的系统方法

    1
    2
    3
    4
    5
    6
    7
    
     - (void)renderInContext:(CGContextRef)ctx;
    
     // example
     UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, [UIScreen mainScreen].scale);
     [view.layer renderInContext:UIGraphicsGetCurrentContext()];
     UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();
    

最开始,我使用的是 UIView 的 drawViewHierarchyInRect 这个方法。 但是这个方法会在视图比较复杂或者尺寸比较大的时候无法成功绘制图片。

后来,我换成了使用 CALayer 的 renderInContext 方法。这次虽然能绘制成功了,但是它又引发了另一个问题:

截图场景中有个使用多层 CAShapeLayer 绘制的圆环进度条,这个进度条不管进度是多少,在生成的图片里面都是满进度(满环)的。 这个问题应该是 renderInContext 方法在渲染图层的时候,发生了一些错误导致的,比如图层顺序错乱了。

后来尝试了很多方法都不管用。直到有次看到了一位外国小哥说 UIScrollView 在绘制图片的时候,只会绘制 bounds 里面的部分(也可以理解为只会绘制可视区域的部分)。

那么,我们就可以将目标 UIView 作为子视图添加到 UIScrollView 上,让他俩”相对运动”,每次绘制一部分视图,然后将这些绘制好的图片拼接起来,就能完美解决无法绘制成功的难题了。

示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// 分段绘制,最后拼接长图
UIImage *snapShotImage = [self drawImageFromView:mainView];

/// 将目标 view 绘制成图片
- (nullable UIImage *)drawImageFromView:(UIView *)view {
    // 图片宽度
    CGFloat imageWidth = view.frame.size.width;
    // 图片高度
    CGFloat totalHeight = view.frame.size.height;
    // 分段数
    NSInteger pieces = (NSInteger)ceil(totalHeight / PIECE_HEIGHT);
    // 剩余未绘制部分的高度
    CGFloat remainHeight = totalHeight;
    UIImage *finalImage;

    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, imageWidth, PIECE_HEIGHT)];
    [scrollView addSubview:view];
    scrollView.contentOffset = CGPointZero;
    scrollView.contentInset = UIEdgeInsetsZero;
    [scrollView layoutSubviews];

    for (int i = 0; i < pieces; i++) {
        // 当前分段的绘制高度。每次取 300
        CGFloat currentPieceHeight = remainHeight >= PIECE_HEIGHT ? PIECE_HEIGHT : remainHeight;
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(imageWidth, currentPieceHeight), NO, 0.0);
        [scrollView drawViewHierarchyInRect:scrollView.bounds afterScreenUpdates:YES];
        UIImage *pieceImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        if (pieceImage == nil) {
            return nil;
        }

        if (finalImage == nil) {
            finalImage = pieceImage;
        } else {
            finalImage = [self mergeImageWithTopImage:finalImage bottomImage:pieceImage];
        }

        remainHeight = remainHeight - currentPieceHeight;

        view.frame = CGRectMake(0, -totalHeight + remainHeight, imageWidth, totalHeight);   // 这里其实是在模拟目标 view 在 UIScrollView 内部滚动特定距离的效果。其实也可以通过设置 UIScrollView 的 contentOffset 来达到这一效果,会更容易理解一些
        [scrollView setNeedsDisplay];
        [scrollView layoutSubviews];
    }

    return finalImage;
}

/// 将上下两个图片拼接成一个图片
- (UIImage *)mergeImageWithTopImage:(UIImage *)topImage bottomImage:(UIImage *)bottomImage {
    CGFloat width = topImage.size.width;
    CGFloat totalHeight = topImage.size.height + bottomImage.size.height;
    CGSize resultSize = CGSizeMake(width, totalHeight);

    UIGraphicsBeginImageContextWithOptions(resultSize, NO, 0.0);
    [topImage drawInRect:CGRectMake(0, 0, width, topImage.size.height)];
    [bottomImage drawInRect:CGRectMake(0, topImage.size.height, width, bottomImage.size.height)];
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return resultImage;
}
本文由作者按照 CC BY-NC-SA 4.0 进行授权