首页 > 解决方案 > 如何在android中旋转按钮的文本?

问题描述

我想旋转按钮上的文字,但我一整天都做不到。

我尝试了自定义垂直按钮,但它没有使按钮中的文本居中。我尝试了 java 和 xml 代码中的所有重力选项。

在此处输入图像描述

这是我的 VerticalButton 代码:

public class VerticalButton extends Button{

    public VerticalButton(Context context, AttributeSet attrs){
        super(context, attrs);
    }

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

    @Override
    protected void onDraw(Canvas canvas){
        TextPaint textPaint = getPaint(); 
        textPaint.setColor(getCurrentTextColor());
        textPaint.drawableState = getDrawableState();

        canvas.save();
        canvas.translate(0, getHeight());
        canvas.rotate(-90);

        canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop());
        getLayout().draw(canvas);
        canvas.restore();
    }
}

我尝试使用旋转按钮android:rotation="-90"

那没有按我想要的方式工作。因为它没有编辑背景大小。

在此处输入图像描述

我尝试使用 Button 和 TextView 进行相对布局,但无法将 TextView 置于 Button 上

提前致谢。

标签: androidxmluser-interface

解决方案


我找到了解决方案。

我编辑了 onDraw 函数。首先获取文本的宽度和高度getTextBounds()

getTextBounds()将 Button 的文本作为参数。

并编辑如下canvas.translate()功能。它使按钮中的文本居中。

@Override
protected void onDraw(Canvas canvas) {
    TextPaint textPaint = getPaint();
    textPaint.setColor(getCurrentTextColor());
    textPaint.drawableState = getDrawableState();
    Rect bounds = new Rect();
    textPaint.getTextBounds("ENTER",0,"ENTER".length(), bounds);

    Log.e("TAG", "onDraw: "+ bounds.width() + " "+bounds.height());
    canvas.save();

    canvas.translate(getWidth()/2 - bounds.height(), (float) (getHeight()/2 + bounds.width()/1.5));
    canvas.rotate(-90);

    getLayout().draw(canvas);
    canvas.restore();
}

推荐阅读