【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));
    }
}
不做过多的阐述,添加了行间距的设置,下图长篇的内容区域则为效果



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值