Android Vertical TextView 文字竖排

竖排文字控件:

转自:http://blog.csdn.net/herbert5069/article/details/8589418


package com.howfun.test;


import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.TextView;


public class VerticalTextView extends TextView{
   final boolean topDown;


   public VerticalTextView(Context context, AttributeSet attrs){
      super(context, attrs);
      final int gravity = getGravity();
      if(Gravity.isVertical(gravity) && (gravity&Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
         setGravity((gravity&Gravity.HORIZONTAL_GRAVITY_MASK) | Gravity.TOP);
         topDown = false;
      }else
         topDown = true;
   }


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


   @Override
   protected boolean setFrame(int l, int t, int r, int b){
      return super.setFrame(l, t, l+(b-t), t+(r-l));
   }


   @Override
   public void draw(Canvas canvas){
      if(topDown){
         canvas.translate(getHeight(), 0);
         canvas.rotate(90);
      }else {
         canvas.translate(0, getWidth());
         canvas.rotate(-90);
      }
      canvas.clipRect(0, 0, getWidth(), getHeight(), android.graphics.Region.Op.REPLACE);
      super.draw(canvas);
   }
}


这样使用来实现文字靠左靠上对齐:



    <com.howfun.test.VerticalTextView
        android:layout_width="450dp"
        android:layout_height="450dp"
        android:textSize="40sp"
        android:layout_marginLeft="100dp"
        android:gravity="bottom|right"
        android:text="Vertical text"
        />

你可能感兴趣的:(Android Vertical TextView 文字竖排)