canvas 的 StaticLayout 定位中心不像 canvas.drawText 那样工作?

StaticLayout positioning center of canvas not working like canvas.drawText?

在使用通常 drawText 绘图时,文本定位在 canvas 的中心。但是我的要求是放置多行文本,所以我必须使用 StaticLayout,但是 StaticLayout 并没有像 drawText 这样放置 这是我到目前为止尝试过的方法。

class TestView : View {

private lateinit var staticLayout: StaticLayout
private lateinit var ststicTextPaint: TextPaint
private lateinit var textPaint: TextPaint
private val helloworld = "Hello world!"

constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
  
}

constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
    context,
    attrs,
    defStyleAttr
) {
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(
    context,
    attrs,
    defStyleAttr,
    defStyleRes
) {
}

override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
    super.onSizeChanged(w, h, oldw, oldh)
    setUp(w, h)
}

private fun setUp(w: Int, h: Int) {
    textPaint = TextPaint(Paint.ANTI_ALIAS_FLAG)
    textPaint.color = Color.BLUE
    textPaint.textSize = 40f
    textPaint.textAlign = Paint.Align.CENTER

    ststicTextPaint = TextPaint(Paint.ANTI_ALIAS_FLAG)
    ststicTextPaint.color = Color.GREEN
    ststicTextPaint.textSize = 40f
  //  textPaint.textAlign = Paint.Align.CENTER

    staticLayout = StaticLayout(
        helloworld,
        ststicTextPaint,
        w,
        Layout.Alignment.ALIGN_CENTER,
        0f,
        0f,
        false
    )
}

override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)
    //Just drawn a rect with cross-hair to know the relative position
    val rect = Rect(0, 0, width, height)
    val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    paint.style = Paint.Style.STROKE
    paint.color = Color.RED
    paint.strokeWidth = 5f
    canvas?.drawRect(rect, paint)
    canvas?.drawLine((width/2).toFloat(), 0F, (width/2).toFloat(), height.toFloat(),paint)
    canvas?.drawLine(0F, (height/2).toFloat(),width.toFloat(), (height/2).toFloat(),paint)

    canvas?.drawText(helloworld, (width / 2).toFloat(), (height / 2).toFloat(), textPaint)
    //   canvas?.drawText(helloworld, (width / 2).toFloat(), (height / 2).toFloat(), textPaint)
    staticLayout.draw(canvas, (width / 2).toFloat(), (height / 2).toFloat())
}

fun StaticLayout.draw(canvas: Canvas?, x: Float, y: Float) {
    canvas?.withTranslation(x, y) {
        draw(canvas)
    }
  }
}

这是我对两者的看法 蓝色的是使用正常 drawText 完成的,绿色的是使用 StaticLayout

伙计们,我解决了这个问题。这是因为我在将 StaticLayout 文本放在中心时忽略了它的宽度。

在这里,我为 StaticLayout 提供了视图的整个宽度。

    staticLayout = StaticLayout(
        "Hello world is helloworld",
        ststicTextPaint,
        w,
        Layout.Alignment.ALIGN_CENTER,
        1f,
        0f,
        false
    )

绘制视图时

staticLayout.draw(canvas, ((width / 2)-staticLayout.width/2).toFloat(), (height / 2).toFloat())

我减去了 `StaticLayout 宽度的一半,这样它就会准确地位于中心。