Android textview text get cut off on the sides with custom font

前端 未结 6 1433
误落风尘
误落风尘 2020-12-30 02:01

This is what happens in the preview and on device:

TextView is nothing special, it just loads the custom font:

public class TestTextView extends App         


        
6条回答
  •  攒了一身酷
    2020-12-30 02:40

    This answer has led me to the right path: https://stackoverflow.com/a/28625166/4420543

    So, the solution is to create a custom Textview and override the onDraw method:

        @Override
        protected void onDraw(Canvas canvas) {
            final Paint paint = getPaint();
            final int color = paint.getColor();
            // 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.setColor(color);
    
            System.out.println("Drawing text info:");
    
            Layout layout = getLayout();
            String text = getText().toString();
    
            for (int i = 0; i < layout.getLineCount(); i++) {
                final int start = layout.getLineStart(i);
                final int end = layout.getLineEnd(i);
    
                String line = text.substring(start, end);
    
                System.out.println("Line:\t" + line);
    
                final float left = layout.getLineLeft(i);
                final int baseLine = layout.getLineBaseline(i);
    
                canvas.drawText(line,
                        left + getTotalPaddingLeft(),
                        // The text will not be clipped anymore
                        // You can add a padding here too, faster than string string concatenation
                        baseLine + getTotalPaddingTop(),
                        getPaint());
            }
        }
    

提交回复
热议问题