gpt4 book ai didi

ios - imageWithCGImage 的内存问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:22:13 26 4
gpt4 key购买 nike

所以这就是要点我有一个程序,它有一个由许多小图像组成的大图像,它获取该图像并将其分成许多较小的图像(如电影的帧),然后用户可以去擦洗通过。

我目前使用的是这种方法

- (NSMutableArray *)createArrayFromImage: (NSData *)largerImageData
{
UIImage *largerImage = [UIImage imageWithData: largerImageData];
int arraySize = (int)largerImage.size.height/largerImage.size.width; //Find out how many images there are
NSMutableArray *imageArray = [[NSMutableArray alloc] init];
for (int i = 0; i < arraySize; i++) {

CGRect cropRect = CGRectMake(0, largerImage.size.width * i, largerImage.size.width, largerImage.size.width);
CGImageRef imageRef = CGImageCreateWithImageInRect([largerImage CGImage], cropRect);
UIImage *image = [UIImage imageWithCGImage: imageRef];
CGImageRelease(imageRef);

[imageArray addObject: UIImageJPEGRepresentation(image, 1.0)];
NSLog(@"Added image %d", i);
}

NSLog(@"Final size %d", (int)[imageArray count]);
return imageArray;
}

但是,由于调用了 UIImageJPEGRepresentation,这非常慢,如果我只是将 UIImage 直接添加到数组中,速度会更快,但是当我在用户擦洗时执行此操作通过数组中的图像,它开始分配大量内存,迫使应用程序最终崩溃。如果有帮助,它会调用 [UIImageView setImage:];。对此的任何帮助将不胜感激。

ED|T:CGImageCreateWithImageInRect 可能会保留导致它占用大量内存的“largerImage”

最佳答案

从本质上讲,您的目标似乎是随机向用户显示图像的特定部分。

如果您只想显示图像的较小部分,则不必创建较小的图像。特别是如果大图像可以立即加载到内存中。而是尝试 View 裁剪来调整图像的可见部分。

例如,你可以试试这个。

  1. 将大图像设置为 UIImageViewsizeToFit
  2. 将 ImageView 放在 UIView 中。
  3. UIView 的框架设置为较小的图像尺寸。
  4. 将外部 UIView
  5. clipsToBounds 设置为 YES
  6. 调整内部UIImageViewtransform来控制可见部分。

这与您对 UIScrollView 所做的基本相同,除了通过用户交互自动滚动。

这是一个代码示例。

- (void)viewDidLoad {
[super viewDidLoad];

UIImageView* v1 = [[UIImageView alloc] init];
[v1 setImage:[UIImage imageWithContentsOfFile:@"large-image.png"]];
[v1 sizeToFit];

UIView* v2 = [[UIView alloc] init];
[v2 setFrame:CGRectMake(0, 0, 100, 100)];
[v2 addSubview:v1];
[v2 setClipsToBounds:YES];

// Set transform later to adjust visible portion.
v1.transform = CGAffineTransformMakeTranslation(-100, -100);

[self.view addSubview:v2];
}

关于ios - imageWithCGImage 的内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24727599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com