Android 文字垂直排列,文字向右旋转90度

public class VerticalTextView extends View {
    private final int ROTATION_ANGLE = 90; // 旋转角度,用于将文本垂直排列
    private String text; // 要显示的文本
    private TextPaint textPaint; // 用于绘制文本的画笔
    private Rect textBounds;// 文本边界
    float x, y;// 文本的绘制位置
    int width, height; / View 的宽度和高度
    private Context mContext;


    public VerticalTextView(Context context) {
        super(context);
        this.mContext = context;
        init();
    }

    public VerticalTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        init();
    }

    public VerticalTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        init();
    }

    private void init() {
        textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);

    }
// 获取文本的边界信息
    public void setText(String text, float size) {
        this.text = text;
        textBounds = new Rect();
        textPaint.setTextSize(size);
        textPaint.setColor(Color.parseColor("#333333"));
        textPaint.getTextBounds(text, 0, text.length(), textBounds);
        requestLayout(); // 请求重新布局
        postInvalidate();// 请求重新绘制
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
       //将文本高度与左内边距和右内边距相加,计算出视图的宽度
        width = textBounds.height() + getPaddingLeft() + getPaddingRight();
       //将文本宽度与上内边距和下内边距相加,计算出视图的高度。
        height = textBounds.width() + getPaddingTop() + getPaddingBottom();
       //设置测量结果
        setMeasuredDimension(width, height);
    }


    @Override
    protected void onDraw(Canvas canvas) {
       //保存当前的画布状态,以便后续的操作不会影响到其他绘制。
        canvas.save();
       //使文本垂直排列,旋转了90度
        canvas.rotate(ROTATION_ANGLE, getWidth() / 2f, getHeight() / 2f);
        if (null != textBounds) {
        //文字水平居中
            x = (getWidth() - textBounds.width()) / 2f - textBounds.left; 
         //文字垂直居中
            y = (getHeight() + textBounds.height()) / 2f - textBounds.bottom;
            if (null != text) {
                //绘制文字
                canvas.drawText(text, x, y, textPaint);
               //恢复之前保存的画布状态,以确保后续的绘制操作不受旋转的影响。
                canvas.restore();
            }
        }
    }
}
<com.signature.view.VerticalTextView
    android:id="@+id/tvInfoNotice"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="3dp"
    android:background="@color/white" />

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值