天天看點

【TextView】自定義TextView中文換行排版問題修複

以下為解決排版核心代碼

public class MyTextView extends TextView {
    private String text;
    private float textSize;
    private float paddingLeft;
    private float paddingRight;
    private float paddingTop;
    private float paddingBottom;
    private int textColor;
    private Paint paint1 = new Paint();
    private float textShowWidth;
    private int lineSpace;//行間距

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        text = this.getText().toString();
        textSize = this.getTextSize();
        textColor = getResources().getColor(R.color.color_black_333333);
        paddingLeft = this.getPaddingLeft();
        paddingRight = this.getPaddingRight();
        paddingTop = this.getPaddingTop();
        paddingBottom = this.getPaddingBottom();
        lineSpace = (int) paddingTop/2;
        paint1.setTextSize(textSize);
        paint1.setColor(textColor);
        paint1.setAntiAlias(true);
    }

    /**
     * 設定畫筆顔色
     * @param color
     */
    public void setPaintColor(int color){
        paint1.setColor(color);
    }
    @Override
    public void onDraw(Canvas canvas) {
        textShowWidth = this.getMeasuredWidth() - paddingLeft - paddingRight;
        int lineCount = 0;
        text = this.getText().toString();
        if (text == null)
            return;
        char[] textCharArray = text.toCharArray();
        float drawedWidth = 0;
        float charWidth;
        int length =textCharArray.length;
        float space=0;
        for (int i = 0; i < length; i++) {
            charWidth = paint1.measureText(textCharArray, i, 1);
            if (textCharArray[i] == '\n') {
                lineCount++;
                drawedWidth = 0;
                continue;
            }
            if (textShowWidth - drawedWidth < charWidth) {
                lineCount++;
                drawedWidth = 0;
            }
            //調整行間距
            if(lineCount==0){
                space = paddingTop;
            }else {
                space = paddingTop+(lineCount+1)*lineSpace;
            }
            canvas.drawText(textCharArray, i, 1, paddingLeft + drawedWidth,
                    (lineCount + 1) * textSize+ space, paint1);
            drawedWidth += charWidth;
        }
        //修正高度
        setHeight((lineCount + 1) * ((int) textSize) +(int) (paddingTop+paddingBottom+(lineCount+1)*lineSpace));
    }
}
           

不做過多的闡述,添加了行間距的設定,下圖長篇的内容區域則為效果

【TextView】自定義TextView中文換行排版問題修複