0

我不明白为什么使用 GCContext 来绘制/合并两个以上的 UIImage 会占用这么多内存。我启用了 ARC,当在 Instruments 中查看我的程序内存使用情况时(使用 VM Tracker 工具),我看到下面的第一个解决方案仅使用两个图像的内存(大约 16 MB DirtySize 和 80 MB ResidentSize),而在 CGContext 中绘图使用我所有 UIImage 的内存量(大约 468 MB DirtySize 和 520 MB ResidentSize),最终导致我的应用程序崩溃。如何确保 CGContext 使用的内存量不超过两个 UIImage 使用的内存量?实际上,我喜欢实现一种双缓冲,以绘制具有相同大小的图像文件(基于.PNG,并且已经具有透明设置)的多个图层,同时具有最小的内存需求和最佳性能。

请注意,我的 ViewController 包含一个“UIImageView *imageView”和一个“CGSize imageSize”属性。

以下代码仅用于检查加载 UIImages 消耗的内存量:

- (void)drawUsingTwoUIImages1:(NSMutableArray *)imageFiles
{
    if ( ! imageFiles.count ) {
        return;
    }
    NSString *imageFile1 = [imageFiles objectAtIndex:0];
    NSString *filePath1 = [[NSBundle mainBundle] pathForResource:imageFile1 ofType:nil];
    UIImage *image1 = [UIImage imageWithContentsOfFile:filePath1];
    UIImage *image2 = nil;
    image1 = [UIImage imageWithContentsOfFile:filePath1];
    for (NSInteger index = 1; index < imageFiles.count; index++) {
        NSString *imageFile2 = [imageFiles objectAtIndex:index];
        NSString *filePath2 = [[NSBundle mainBundle] pathForResource:imageFile2 ofType:nil];
        image2 = [UIImage imageWithContentsOfFile:filePath2];
    }
}

我想在我的最终应用程序中使用的下一个代码,以显示所有绘制的图像文件。我怀疑需要按照 CGContext 处理的顺序或者可能是 CGLayerRef 的顺序来完成一些巧妙的技巧。如果有人能告诉我如何做到这一点,或者想出工作代码,我将再次进入编码天堂!

- (void)drawUsingTwoUIImages2:(NSMutableArray *)imageFiles
{
    _imageView.image = nil;
    if ( ! imageFiles.count ) {
        return;
    }
    NSString *imageFile1 = [imageFiles objectAtIndex:0];
    NSString *filePath1 = [[NSBundle mainBundle] pathForResource:imageFile1 ofType:nil];
    UIImage *image1 = [UIImage imageWithContentsOfFile:filePath1];
    UIImage *image2 = nil;
    for (NSInteger index = 1; index < imageFiles.count; index++) {
        if ( ! UIGraphicsGetCurrentContext() ) {
            UIGraphicsBeginImageContext(_imageSize);
        }
        NSString *imageFile2 = [imageFiles objectAtIndex:index];
        NSString *filePath2 = [[NSBundle mainBundle] pathForResource:imageFile2 ofType:nil];
        image2 = [UIImage imageWithContentsOfFile:filePath2];
        [image1 drawAtPoint:CGPointMake(0., 0.)];
        [image2 drawAtPoint:CGPointMake(0., 0.)];
        image1 = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    _imageView.image = image1;
}

以上真的让我发疯了,有没有人在这里看到我缺少的东西,或者知道该怎么做才能获得最大的性能和最小的内存使用?!

4

1 回答 1

1

I already figured out that the way to go is using CATiledLayer and where needed tile your image data in various scale-sizes. Digging around in Apple's example code and searching in StackOverflow helped me to solve this issue.

于 2013-03-27T15:26:08.127 回答