Cách sửa lỗi kí tự đầu bị cắt trong TextView khi dùng custom font

Categories Story
enter image description here
Android TextView

Chẳng là hôm nay mình gặp 1 bug như hình cover nên chia sẻ lại kinh nghiệm cho các Pác đỡ mất công tìm

Tình hình là em sử dụng 1 custom font trong app và bị vấn đề là mất góc của mốt số kí tự như j, f, e,.. khi nó nằm ở đầu dòng. Em đã gắng dùng thử 1 vài cách để fix như là thêm padding start, padding left,… cho vào 1 layout khác và dùng margin cũng như padding nhưng cũng không ăn thua.

Do đó mình search thử 1 vài từ khóa xem có ai bị giống vậy không. May quá có các Pác ạ, đây là lỗi khi sử dụng 1 custom font trên TextView hoặc EditText. Cách xử lý là phải custom lại TextView bằng cách extend lại AppCompatTextView rồi override lại onDraw sau đó viết code để vẽ lại. Các bạn có thể tham khảo code Kotlin như dưới đây:

// This custom text view will avoid cutting off on the sides with custom font
class TextViewWithoutClipping : AppCompatTextView {
    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs,
            defStyleAttr)

    override fun onDraw(canvas: Canvas) {
        val color: Int = paint.color
        // Draw what you have to in transparent
        // This has to be drawn, otherwise getting values from layout throws exceptions
        setTextColor(Color.TRANSPARENT)
        super.onDraw(canvas)
        // setTextColor invalidates the view and causes an endless cycle
        paint.color = color
        for (i in 0 until layout.lineCount) {
            val start = layout.getLineStart(i)
            val end = layout.getLineEnd(i)
            val line = text.substring(start, end)
            val left = layout.getLineLeft(i)
            val baseLine = layout.getLineBaseline(i)
            canvas.drawText(line,
                    left + totalPaddingLeft,  // The text will not be clipped anymore
                    // You can add a padding here too, faster than string string concatenation
                    baseLine + totalPaddingTop.toFloat(),
                    paint)
        }
    }
}

Hy vọng bài viết này giúp ích gì đó với các Pác.

Nguồn tham khảo:

https://stackoverflow.com/questions/44074858/android-textview-text-get-cut-off-on-the-sides-with-custom-font/44218468#44218468

https://stackoverflow.com/questions/28576797/text-being-cut-off-from-front-for-a-particular-font/28625166#28625166

No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *