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" />