java - 如何在 Java Canvas 中绘制 JSON 文本?

标签 java android json android-canvas pretty-print

如何在 Android Canvas 中编写具有漂亮格式的 JSON 对象/字符串?

例如,

val jsonText = "{"profile":{"name": "Robert","account_id": "31"}}"

将被绘制到看起来像的Canvas

enter image description here

最佳答案

Canvas functions have some limitations as it draws all text in single line. If the width of the text exceeds the width of the Canvas, the text will be clipped. hence we use staticLayout for the same to show text in paragraph or multi-line approach.

下面的代码用于在 Canvas 中显示 json 格式的文本,其中 json 从 Assets 文件加载。

fun drawTextOnCanvas(activity: FragmentActivity) {
var canvas = Canvas(bitmap)
var textPaint=TextPaint()
textPaint.density=20f
textPaint.bgColor=Color.BLACK

val jsonText = activity.loadJSONFromAsset("demo.json")
val jsonObject = JSONObject(jsonText);
val text=jsonObject.toString(1)
val staticLayout=StaticLayout.Builder.obtain(text,0,text.length,textPaint,150)

staticLayout.build().draw(canvas)}

希望这对您有所帮助!

关于java - 如何在 Java Canvas 中绘制 JSON 文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58444365/

相关文章:

android - 使用 firebase 添加额外的用户信息

安卓服务 : life cycle considerations

android - navigator.geolocation.GetCurrentPosition 抛出 "The last location provider was disabled"错误

ios - 显示 JSON 响应中的 cell.textLabel.text

java - 在 Java 中的 JButton 上绘画

java - 使用一致性缓存的开销

java - Spring Security 仅用一条路径处理不同用户

java - 程序只会输出else语句

java - 有没有一种方法可以很好地使用 gson 来获取包含 java 中具有 4 个变量的数组的列表

python - 解析随每个 API 查询而变化的 JSON 对象