我正在编写一个简单的 Android 游戏,我希望我的游戏 UI HUD 仅显示两位小数(即仅数百秒)来显示所花费的时间、耗时等。我的代码示例如下:
canvas.drawText("Fastest: " + formatTime(fastestTime) + " S", 10, 20, paint);
formatTime 返回以毫秒为单位的时间。 (即 54.335 S)。这对我的需求来说毫无用处。我按照之前其他问题中的建议尝试了 DecimalFormat,但没有成功。我怀疑问题出在 canvas.drawText 而不是“简单”System.out.println()
非常感谢任何帮助。
最佳答案
我想提出两种不同的方法来实现您的目标:
<强>1。绘制文本()
查看 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(这会影响字符串的长度,从而影响结束索引)。
- 如果“formatTime()”方法返回一个字符串,您可以获得“.”的索引。并加 2 以添加毫秒。
- 如果“formatTime()”方法返回四舍五入 double ,则必须将 double 转换为字符串并应用步骤 1。
drawText() 调用现在如下所示:
String time = formatTime(fastestTime);
int endIndex = time.indexOf('.') + 5;
canvas.drawText("Fastest: " + formatTime(fastestTime) + " S", 0, endIndex, 10, 20, paint);
<强>2。裁剪字符串
如果我的第一个解决方案不起作用(我还没有尝试过),您可以简单地将字符串裁剪为毫秒并绘制整个字符串。
我假设格式时间返回一个字符串(如果不将其转换为字符串并继续)。
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);
关于java - Android游戏,仅显示两位小数(仅数百秒)的游戏UI HUD花费时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57110283/