如何在 Android Canvas
中编写具有漂亮格式的 JSON
对象/字符串?
例如,
val jsonText = "{"profile":{"name": "Robert","account_id": "31"}}"
将被绘制到看起来像的Canvas
,
最佳答案
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/