自定义TextView和文本绘图

时间:2012-09-13 19:03:08

标签: android android-canvas android-custom-view

我正在尝试实现自定义视图来显示文本,但是绘制文本时出现问题(文本为红色,视图背景为绿色):

enter image description here

源代码位于pastebin

2 个答案:

答案 0 :(得分:3)

你的onDraw()方法存在一些问题。由于您没有明确更改文本对齐方式,因此默认情况下文本对齐为左侧。在此模式下,文本从左(x)绘制到基线(y)的正上方。在你的代码x = 0和y = 0,因此文本开始从x = 0向右和基线y = 0上方绘制,因此你的文字是不可见的。这是您的代码的修改版本:

公共类FastTextView扩展了View {

private Context mContext;
private String mText = "";
private int mTextSize;
private Paint mPaint;

private int paddingLeft   = 0;
private int paddingRight   = 0;
private int paddingTop    = 0;
private int paddingBottom = 0;

private int fontSize = 100;

public void setText(String text)
{
    mText = text;
}

public FastTextView (Context context)
{
    super(context);
    initialize();
}

public FastTextView (Context context, AttributeSet attrs)
{
    super(context, attrs);
    initialize();
}

public void setPaddingLeft(int padding)
{
    paddingLeft = padding;
}

public void setPaddingRight(int padding)
{
    paddingRight = padding;
}

public void setPaddingBottom(int padding)
{
    paddingBottom = padding;
}

public void setPaddingTop(int padding)
{
    paddingTop = padding;
}

public void setFontSize(int size)
{
    fontSize = size;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    Rect rect = new Rect();
    mPaint.getTextBounds(mText.toString(), 0, mText.length(), rect);

    int width = Math.max(rect.width(), getSuggestedMinimumWidth()) + paddingLeft + paddingRight;
    int height = Math.max(rect.height(), getSuggestedMinimumHeight()) + paddingTop + paddingBottom;

    setMeasuredDimension(width, height);
}

/**
 * Initialize the view
 */
private void initialize()
{
    mContext = getContext();
    mPaint = new Paint();
    mPaint.setColor(Color.RED);
    mPaint.setTextSize(fontSize);
    mPaint.setTextAlign(Align.LEFT);
    setBackgroundColor(Color.GREEN);
}

@Override
protected void onDraw(Canvas canvas)
{
    super.onDraw(canvas);
    canvas.drawColor(Color.BLUE);
    int x = paddingLeft;
    int y = paddingTop + fontSize;

    if (mText.length() > 0) {
        canvas.drawText(mText, x, y-fontSize/4, mPaint);
    }
}

}

答案 1 :(得分:2)

而不是使用(L 91)在视图顶部绘制文本:

canvas.drawText(mText, 0, mText.length() - 1, 0, 0, mPaint);

尝试:

canvas.drawText(mText, 0, mText.length() - 1, 0, canvas.getHeight(), mPaint);

请注意,对齐设置存储在Paint变量中。因此,如果您的文本仍未正确绘制,则应该更改它。