有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓如何在Java画布中绘制JSON文本?

如何在Android Canvas中编写格式非常好的JSON对象/字符串

比如说,

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

将被绘制到一个Canvas中,如下所示:

enter image description here


共 (2) 个答案

  1. # 1 楼答案

    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.

    下面的代码用于在画布中显示json格式的文本,其中json是从资产文件加载的

    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)}
    

    希望这有帮助

  2. # 2 楼答案

    生成PDF

    import android.graphics.Color
    import android.graphics.Paint
    import android.graphics.pdf.PdfDocument
    import com.google.gson.GsonBuilder    
    
    class PdfGeneratorService(){
    
        private val ROW_INC = 20F
        private val COL_INC = 15F
        
        fun jsonFormat(jsonStr: String): String {
    
            var indentCount = 0
    
            val builder = StringBuilder()
            for (c in jsonStr) {
                if (indentCount > 0 && '\n' == builder.last()) {
                    for (x in 0..indentCount) builder.append("    ")
                }
                when (c) {
                    '{', '[' -> {
                        builder.append(c).append("\n")
                        indentCount++
                    }
                    ',' -> builder.append(c).append("\n")
                    '}', ']' -> {
                        builder.append("\n")
                        indentCount 
                        for (x in 0..indentCount) builder.append("    ")
                        builder.append(c)
                    }
                    else -> builder.append(c)
                }
            }
    
            return builder.toString()
        }
    
        private fun createPdf(textToPdf: String) {
            try {
                val gSon = GsonBuilder().setPrettyPrinting().create()
                val text = gSon.toJson(jsonFormat(textToPdf))
    
                val rawLines = text.split("\\n")
                val jsonLines = rawLines.map { it.replace("\\", "") }
                val maxLengthString = jsonLines.maxBy { it.length }
    
                val paint = Paint()
                paint.color = Color.BLACK
                paint.fontSpacing
    
                val pageWidth = paint.measureText(maxLengthString).toInt() + 2 * COL_INC.toInt() // 2, two side padding
                val pageHeight = (ROW_INC * rawLines.size + ROW_INC).toInt()
    
                val document = PdfDocument()
                val pageInfo: PdfDocument.PageInfo = PdfDocument.PageInfo.Builder(pageWidth, pageHeight, 1).create()
                val page: PdfDocument.Page = document.startPage(pageInfo)
                val canvas = page.canvas
    
                for (line in jsonLines) {
                    canvas.drawText(line, column, row, paint)
                    row += ROW_INC
                }
    
                document.finishPage(page)
                document.writeTo(FileOutputStream(File(PATH_TO_PDF_FILE)))
                document.close()
            }catch (e: java.lang.Exception){
                Log.e("classTag", e)
            }
        }
    }
    

    您可以找到关于如何使用Gson的文章