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

标签 java android game-development time-format

我正在编写一个简单的 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(这会影响字符串的长度,从而影响结束索引)。

  1. 如果“formatTime()”方法返回一个字符串,您可以获得“.”的索引。并加 2 以添加毫秒。
  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/

相关文章:

java - 如何将字符串 23323.00 转换为长整型

java - 使用 Jena 读取限制值

java - 从 Java 调用 javascript 函数

python - 如何在 pygame 中生成多个敌人

java - Retrofit2 状态码为 200 但 json 结构不同于数据模型类时的处理条件

java - java中的xml utf-8编码错误

没有 Intent 过滤器的 Android BroadcastReceiver

java - Android ImageView 不显示图像?

c++ - SDL 2 blitting BMP 文件

rust - Rust 中的动态类型实体组件系统