将整数变量赋给图像

时间:2014-06-05 16:33:25

标签: ios objective-c ios7 sprite-kit

所以我有一些从0.png到9.png的图像,它们将被用于得分。 现在我希望根据当前分数显示图像。我可以这样做:

scoreImage = [UIImage imageNamed:[NSString stringWithFormat:@"%d.png", score]];

上面的代码意味着我必须创建无限数量的图像来覆盖分数。 有没有更有效的方法来做到这一点?每个数字仅使用10个图像,例如0.png 1.png 2.png ... 9.png

提前致谢

1 个答案:

答案 0 :(得分:1)

MOST这样做的有效方法是使用直接显示文本的视图对象,如UILabel。然后,您只需将其字体,大小和样式设置为所需的值,并将其文本设置为您想要的值。

您可以制作仅包含数字的自定义字体,并使用它。我从未创建过自定义字体,但我知道它是可能的。

如果失败,您可以创建一个包含4个UIImageView对象的自定义ScoreView类。它将具有整数属性分数,当您设置分数值时,它会将正确的数字图像安装到其不同的组件图像视图中。

计算数字值的代码可能如下所示:

int score = 7596;
int remainder = score;

int thousandsValue = remainder / 1000;
remainder -= thousandsValue*1000;

int hundredsValue = remainder /100;
remainder -= hundredsValue*100;

int tensValue = remainder/10;
int onesValue = remainder % 10;

NSLog(
      @"For %d, thousandsValue = %d, hundredsValue = %d, tensValue = %d,  onesValue = %d",
      score,
      thousandsValue,
      hundredsValue,
      tensValue,
      onesValue
      );

然后使用这些值为您的千位数,百位数,十位数和一位数字图像视图构建图像文件名。

最后,将图像加载并安装到每个imageView中。