首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >优化UIColor动画

优化UIColor动画
EN

Stack Overflow用户
提问于 2012-12-14 20:11:53
回答 1查看 194关注 0票数 0

我正努力让这个GIF显示在我正在构建的iPhone应用程序上。我现在正在分析这个应用程序,我意识到我一直在被分配一个UIColor,它几乎使用了手机的所有CPU。

我整个上午都在努力优化这个函数,我用它来创建和运行动画。如果有人有洞察力,我会非常感激的。

我只是想把这个UIColor从for语句中提取出来,但是也许有人会发现我可以用更好的方法来做这件事。

代码语言:javascript
复制
- (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];
     }];
}

编辑:请求发布代码

代码语言:javascript
复制
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,超出了空数组的界限。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-14 20:31:44

这是对H2CO3的评论的更明确的解释:

定义一些类属性:

代码语言:javascript
复制
@property (nonatomic, retain) NSMutableArray* colors;
@property (nonatomic, assign) currentColorIndex;

然后有一个单一的颜色初始化例程:

代码语言:javascript
复制
- (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不需要继续创建颜色数组:

代码语言:javascript
复制
- (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];
     }];
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13885577

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档