Android TextView 竖向显示(字体长度对字体位置有影响)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012246458/article/details/85234205

需求:

Android字体竖向显示

1、使用android:rotation="90";不足:如果字体很长,那么会有很长的距离。

2、自定义TextView竖向布局。消除了字体长度对字体位置有影响

1、rotation使用(不建议)

效果图:

代码:

<TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:rotation="90"
            android:text="① 请拍摄身份证人像面"
            android:textColor="@color/font_white"
            android:visibility="gone" />

如图:由于 ① 请拍摄身份证人像面 这个字体太长,导致右侧右边距。所以需要自定义TextView

2、自定义TextView(建议)

效果图:

引用代码:

<com.baofu.yunfutong.ui.view.VerticalTextView
            android:id="@+id/tv_topText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:text="① 请拍摄身份证人像面"
            android:layout_centerVertical="true"
            android:textColor="@color/font_white" />

VerticalTextView代码:

扫描二维码关注公众号,回复: 5656570 查看本文章
package com.baofu.yunfutong.ui.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.TextView;

/**
 * TextView竖向显示
 * Created by zst on 2018/12/6.
 */
@SuppressLint("AppCompatCustomView")
public class VerticalTextView extends TextView {
    final boolean topDown;


    public VerticalTextView(Context context, AttributeSet attrs){
        super(context, attrs);
        final int gravity = getGravity();
        if(Gravity.isVertical(gravity) && (gravity&Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
            setGravity((gravity&Gravity.HORIZONTAL_GRAVITY_MASK) | Gravity.TOP);
            topDown = false;
        }else
            topDown = true;
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        super.onMeasure(heightMeasureSpec, widthMeasureSpec);
        setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
    }


    @Override
    protected boolean setFrame(int l, int t, int r, int b){
        return super.setFrame(l, t, l+(b-t), t+(r-l));
    }


    @Override
    public void draw(Canvas canvas){
        if(topDown){
            canvas.translate(getHeight(), 0);
            canvas.rotate(90);
        }else {
            canvas.translate(0, getWidth());
            canvas.rotate(-90);
        }
        canvas.clipRect(0, 0, getWidth(), getHeight(), android.graphics.Region.Op.REPLACE);
        super.draw(canvas);
    }
}

如图:消除了字体长度对于字体位置的影响。

猜你喜欢

转载自blog.csdn.net/u012246458/article/details/85234205