Android 游戏,在游戏中花费的时间只显示两位小数(仅数百秒) UI HUD

Android game, displaying only two decimals (only hundreds of seconds) for time spent in the game UI HUD

我正在编写一个简单的 Android 游戏,我希望我的游戏 UI HUD 仅显示两位小数(即仅数百秒)来显示所花费的时间、经过的时间以及相似的。我的代码示例之一是:

canvas.drawText("Fastest: " + formatTime(fastestTime) + " S", 10, 20, paint);

formatTime returns 以毫秒为单位的时间。 (即 54.335 S)。这对我的需求没有用。正如之前在其他问题中所建议的那样,我尝试了 DecimalFormat,但没有成功。我怀疑问题出在 canvas.drawText 而不是 "simply" System.out.println()

非常感谢任何帮助。

我想提出两种不同的方法来达到你的目标:

1. drawText()

查看 Canvas 的文档,似乎有一种方法也接受要绘制的字符串的第一个和最后一个索引。

drawText(CharSequence text, int start, int end, float x, float y, Paint paint)

Draw the specified range of text, specified by start/end, with its origin at (x,y), in the specified Paint.

我建议将您的代码更改为:

canvas.drawText("Fastest: " + formatTime(fastestTime) + " S", 0, 7, 10, 20, paint);

开始:0, 结束:7(因为“54.33 S”也包括点)。

一个可能的问题是秒数小于 10 或大于 100(这会影响字符串的长度,从而影响结束索引)。

  1. 如果"formatTime()"方法returns一个String,就可以获得'.'的索引并加 2 以增加毫秒数。
  2. 如果 "formatTime()" 方法 returns 一个四舍五入的双精度数,则必须将双精度数转换为字符串并应用步骤 1。

drawText() 调用现在如下所示:

String time = formatTime(fastestTime);
int endIndex = time.indexOf('.') + 5;
canvas.drawText("Fastest: " + formatTime(fastestTime) + " S", 0, endIndex, 10, 20, paint);  

2。裁剪字符串

如果我的第一个解决方案不起作用(我没有尝试过),您可以简单地将字符串裁剪到毫秒并绘制整个字符串。

我假设格式化时间 returns 是一个字符串(如果没有将其转换为字符串并继续)。

String time = formatTime(fastestTime);
int endIndex = time.indexOf('.') + 3; //the endIndex of String.substring() is exclusive.

canvas.drawText("Fastest: " + time.substring(0, endIndex) + " S", 10, 20, paint);