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();// 请求重新绘制}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {//将文本高度与左内边距和右内边距相加,计算出视图的宽度width = textBounds.height() + getPaddingLeft() + getPaddingRight();//将文本宽度与上内边距和下内边距相加,计算出视图的高度。height = textBounds.width() + getPaddingTop() + getPaddingBottom();//设置测量结果setMeasuredDimension(width, height);}@Overrideprotected 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.VerticalTextViewandroid:id="@+id/tvInfoNotice"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="3dp"android:background="@color/white" />
