【问题标题】:In Android, can a StaticLayout with Spans be Align.CENTER'ed?在 Android 中,带有 Spans 的 StaticLayout 可以 Align.CENTER\'ed 吗?
【发布时间】:2022-11-02 20:44:59
【问题描述】:

我正在尝试使用StaticLayoutCharSequences 与Spans 居中。 textPaint.textAlign = Paint.Align.LEFT 时一切正常。

但是,如果我设置textPaint.textAlign = Paint.Align.CENTER,一切都会变得不稳定。

看起来好像跨越的部分被剥离,然后“居中计算”完成,然后呈现文本。

在我的代码中,对齐方式是通过doCenter 更改的。

    override fun onDraw(canvas: Canvas) {
        //:

        val doCenter = true
        val textWidPct = 0.90F
        dpToUse = 10
        val cs = clueDisplayText

        val xPos: Float
        if (doCenter) {
            xPos = clueTextRect.exactCenterX()
            textPaint.textAlign = Paint.Align.CENTER
        } else {
            xPos = clueTextRect.width() * ((1 - textWidPct) / 2)
            textPaint.textAlign = Paint.Align.LEFT
        }
        textPaint.typeface = k.typefaceNormal
        textPaint.textSize = j.dpToPx(dpToUse).toFloat()
        textPaint.color = cc.Black

        val wid = (width * textWidPct).round()
        val staticLayout = StaticLayout.Builder
            .obtain(cs, 0, cs.length, textPaint, wid)
            .build()

        val yPos = clueTextY + j.dpToPx(dpToUse)
        canvas.withTranslation(xPos, yPos) {
            staticLayout.draw(canvas)
        }
    }

最后一点:

改变

            canvas.withTranslation(xPos, yPos) {
                staticLayout.draw(canvas)
            }

简单地

            staticLayout.draw(canvas)

将输出移动到左上角,但它同样不稳定。

我已经对此进行了研究,但找不到任何相关信息。不在SO这里,也不在网络上的其他地方。我确实发现了一些关于 CSS 的同一类型问题的讨论,其中的结论似乎是“无法完成”。

我在这里错过了一些简单的东西吗?还是我需要采取更复杂的方法?或者这是不可能的?

注意:minSdk 是 23 (M / Marshmallow)

【问题讨论】:

    标签: android drawtext


    【解决方案1】:

    我发现了我的错误。决定为可能遇到此问题的任何人发帖。

    不要使用

        textPaint.textAlign = Paint.Align.CENTER
    

    StaticLayout.Builder 中设置对齐方式

        val staticLayout = StaticLayout.Builder
            .obtain(cs, 0, cs.length, textPaint, wid)
            .setAlignment(Layout.Alignment.ALIGN_CENTER)
            .build()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-01
      • 1970-01-01
      • 2011-02-23
      • 2017-06-06
      • 1970-01-01
      • 2018-09-24
      • 1970-01-01
      • 2011-08-28
      相关资源
      最近更新 更多