ios - 将整数变量分配给图像

标签 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

提前致谢

最佳答案

最有效的方法是使用直接显示文本的 View 对象,例如 UILabel。然后您可以简单地将其字体、大小和样式设置为所需的值,并将其文本设置为您想要的值。

您可以设计一个只包含数字的自定义字体,然后使用它。我从未创建过自定义字体,但我知道这是可能的。

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

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

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 构建图像文件名。

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

关于ios - 将整数变量分配给图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24065562/

相关文章:

ios - 如何从 iOS 中的 GLKVector2 获取 vectorLeft 值?

iphone - UITableView:NSMutableArray没有出现在表中

ios7 - iOS 7 中没有显示成就通知横幅

ios - 相机捕获叠加层上的动画角色

ios - 如何在 JSON 中制作字典字典?

ios - 控件可能会到达非空函数的结尾 - 使用 Apple 代码时

ios - 从 Collection View Xcode 中删除 Collection View Cell

ios - 带有阴影、圆角和自定义 drawRect 的 UIView

uiwebview - iOS7 UIWebivew Youtube MPMediaPlayer无法正常工作

ios - 流式音频文件在弹出到 View Controller 后正在播放