iOS - 创建像照片应用程序的照片查看器
我正在尝试在iOS中创建像Apple照片应用程序一样的照片查看器。 布局是好的,但它收到内存警告,然后崩溃。为什么?即使我从应用程序文档文件夹加载7/8图像,也会发生这种情况。我有没有用特定的系统管理内存?我用ARC与iOS 5.iOS - 创建像照片应用程序的照片查看器
编辑:
的代码:
for (int i=0; i<[dataSource count]; i++) {
UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[dataSource objectAtIndex:i] forState:UIControlStateNormal];
[[button titleLabel] setText:[NSString stringWithFormat:@"%i",i+1]];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[[button layer] setBorderWidth:1];
[[button layer] setBorderColor:[UIColor darkGrayColor].CGColor];
if (i==0) {
[button setFrame:CGRectMake(x, y, width, height)];
} else {
if (i%5==0) {
nRow++;
x=18;
[button setFrame:CGRectMake(x, (y*nRow), width, height)];
} else {
[button setFrame:CGRectMake(x+space+width, (y*nRow), width, height)];
x=button.frame.origin.x;
}
}
[[self view] addSubview:button];
}
此代码的主要部分是前6行,之后是所有的x和y。 dataSource是一个声明为属性(非原子,强大)的NSArray。它包含UIImage对象。
你应该懒洋洋地加载在你的图片结合重新使用按钮来说明大量图像的可能性。
要实现:
- 保持路径的图像文件数据阵列,而不是UIImage的对象英寸使用imageWithContentsOfFile从路径中获取图像:当你需要它时。
- 将第一个z按钮加载到滚动视图中,其中z是一次显示在屏幕上的数字加上一行的值。
- 将我们当前所在的UIViewController设置为scrollview的委托,并通过重新定位按钮并设置适当的图像和目标来响应偏移中的更改。
此外,如果7/8图像崩溃你的应用程序,这听起来像你正在处理一些非常大的图像文件。尝试在文档目录中提供缩略图大小的版本(无论您的按钮的大小是否正确),或者图像是动态的,请参阅this post了解操作方法。
如果您使用的可能ImageNamed,这篇文章帮助我很多:
http://www.alexcurylo.com/blog/2009/01/13/imagenamed-is-evil/
主要
不要用[UIImage的imageNamed对于图像的任何显著量。这是EVIL。它会降低你的应用程序和/或Springboard,即使你的应用程序只使用了几乎一小撮的内存。
和
这是更好地实现自己的高速缓存
,这里是所提出的缓存形象的例子:
- (UIImage*)thumbnailImage:(NSString*)fileName
{
UIImage *thumbnail = [thumbnailCache objectForKey:fileName];
if (nil == thumbnail)
{
NSString *thumbnailFile = [NSString stringWithFormat:@"%@/thumbnails/%@.jpg", [[NSBundle mainBundle] resourcePath], fileName];
thumbnail = [UIImage imageWithContentsOfFile:thumbnailFile];
[thumbnailCache setObject:thumbnail forKey:fileName];
}
return thumbnail;
}
我不使用imageNamed – 2011-12-20 15:40:31
@BartłomiejSemańczyk感谢您的提示,我已经更新了我的答案 – 321zeno 2016-02-03 12:44:00
@ user523234代码添加 – 2011-12-20 15:40:12
@ user523234简单的接收内存警告,然后崩溃 – 2011-12-21 10:44:53