我正努力让这个GIF显示在我正在构建的iPhone应用程序上。我现在正在分析这个应用程序,我意识到我一直在被分配一个UIColor,它几乎使用了手机的所有CPU。
我整个上午都在努力优化这个函数,我用它来创建和运行动画。如果有人有洞察力,我会非常感激的。
我只是想把这个UIColor从for语句中提取出来,但是也许有人会发现我可以用更好的方法来做这件事。
- (void)doBackgroundColorAnimation
{
static NSInteger i = 0;
int count = 34;
NSMutableArray *colors = [[NSMutableArray alloc] initWithCapacity:count];
for (int i=1; i<=34; i++) {
NSString *strImgName = [NSString stringWithFormat: @"layer%d.png", i];
UIColor *image = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:strImgName]];
if (image) {
[colors addObject:image];
}
}
if (i >= [colors count]) {
i = 1;
}
[UIView animateWithDuration:0.05f
animations:^{
self.animationView.backgroundColor = [colors objectAtIndex:i];
} completion:^(BOOL finished) {
++i;
[self doBackgroundColorAnimation];
}];
}编辑:请求发布代码
NSMutableArray *colors = [[NSMutableArray alloc] initWithCapacity:count];
static NSString *strImgName;
UIColor *image = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:strImgName]];
for (int i=1; i<=34; i++) {
strImgName = [NSString stringWithFormat: @"layer%d.png", i];
if (image) {
[colors addObject:image];
}
}返回-__NSArrayM objectAtIndex::index 1,超出了空数组的界限。
发布于 2012-12-14 20:31:44
这是对H2CO3的评论的更明确的解释:
定义一些类属性:
@property (nonatomic, retain) NSMutableArray* colors;
@property (nonatomic, assign) currentColorIndex;然后有一个单一的颜色初始化例程:
- (void)calledDuringInit
{
self.colors = [NSMutableArray array];
for (int i=1; i<=34; i++)
{
NSString *strImgName = [NSString stringWithFormat: @"layer%d.png", i];
UIColor *image = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:strImgName]];
if (image)
{
[self.colors addObject:image];
}
}
}此时,doBackgroundColorAnimation不需要继续创建颜色数组:
- (void)doBackgroundColorAnimation
{
if (self.currentColorCount >= [self.colors count])
{
self.currentColorCount = 1;
}
[UIView animateWithDuration:0.05f
animations:^{
self.animationView.backgroundColor = [self.colors objectAtIndex:self.currentColorCount];
} completion:^(BOOL finished) {
++self.currentColorCount;
[self doBackgroundColorAnimation];
}];
}https://stackoverflow.com/questions/13885577
复制相似问题