Android中带Span的StaticLayout能否设置Align.CENTER对齐?
问题:StaticLayout带Span文本居中对齐异常
我尝试使用StaticLayout对带有Span的CharSequence进行居中对齐。当设置textPaint.textAlign = Paint.Align.LEFT时,一切正常。但设置为Paint.Align.CENTER后,显示出现异常,看起来像是Span部分被剥离,先计算居中再渲染文本。
我的代码通过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) } }
补充说明:将画布平移的代码改为直接调用staticLayout.draw(canvas)后,文本移到左上角,但显示仍然异常。我在技术社区未找到相关解决方案,类似CSS问题结论是无法实现。请问我是否遗漏了简单的解决方法,或是需要复杂实现,还是该需求本身无法完成?
注:最低兼容SDK版本为23(Marshmallow)
内容的提问来源于stack exchange,提问作者Free Dorfman
相关产品推荐
相关产品推荐

