在画布上垂直绘制文本

时间:2012-02-13 14:50:57

标签: android rotation android-canvas drawtext

我想学习如何在画布上绘制垂直文本。对不起,也许是愚蠢的问题,但我无法解决这个问题。我可以这样做:

 if (i ==10)
      {
          this_str2 = "0.00";
      }  


              canvas.save();
              canvas.rotate(-90,190,90);
              canvas.drawText(this_str2,  x_guide +50, drawSizes[1] + drawSizes[3]  -  (i *    drawSizes[3] / 10) +20, paint);
              canvas.restore();
      }

但它没有在X上正确显示,Y是此问题的任何其他解决方案7

1 个答案:

答案 0 :(得分:5)

尝试使用此自定义textview,我不记得我从哪里开始(如果在StackOverflow中),如果有人记得,请在评论中发布一个链接。

import android.content.Context;
import android.graphics.Canvas;
import android.text.TextPaint;
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 void onDraw(Canvas canvas)
    {
        TextPaint textPaint = getPaint();
        textPaint.setColor(getCurrentTextColor());
        textPaint.drawableState = getDrawableState();

        canvas.save();

        if (topDown)
        {
            canvas.translate(getWidth(), 0);
            canvas.rotate(90);
        }
        else
        {
            canvas.translate(0, getHeight());
            canvas.rotate(-90);
        }

        canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop());

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