android - 如何在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 上
提前致谢。
解决方案
我找到了解决方案。
我编辑了 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();
}
推荐阅读
- docker - 如何找到 docker 容器的共享内存大小?
- android-recyclerview - 键盘与聊天消息重叠
- android - AnimatedVectorDrawable 未在 Android 8.0.0 上运行
- python - Pyinstaller 可执行文件无法工作/运行。可能是什么问题?
- javascript - 通过 JavaScript 为类型文件的输入元素设置 CSS
- mysql - 按字母顺序排列的数据透视表
- android - 在所有活动中共享相同的片段状态
- google-cloud-firestore - Kivy buildozer Firestore 错误 - ModuleNotFoundError:没有名为“google.cloud”的模块
- html - 如何在vuetify中居中对齐一组浮动按钮?
- css - 如何使用 vuetify 制作移动响应式导航栏