在自定义视图中绘制文本,canvas.drawText不会显示

时间:2014-05-15 06:11:05

标签: android view

我试图在自定义视图中绘制文本,该视图将图像作为背景。正在绘制三件事。

  • 圈子后面的位图
  • 红圈和
  • 文字覆盖。

目前圆圈和位图画得很完美,但文字没有显示。

自定义视图代码。

public class NotificationButtonView extends Button
{
private int mNumberOfNotifications = 0;
private Paint mNotificationPaint = new Paint();
private Paint mTextPaint = new Paint();

public NotificationButtonView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}
public NotificationButtonView(Context context, AttributeSet attrs) {
    super(context, attrs);
}
public NotificationButtonView(Context context) {
    super(context);
}

public void setNotificationNumber(int number)
{
    this.mNumberOfNotifications = number;
    this.invalidate();
}

public void addNotification()
{
    this.mNumberOfNotifications++;
    this.invalidate();
}

@Override
protected void onAttachedToWindow() 
{
    super.onAttachedToWindow();

    mNotificationPaint.setColor(Color.rgb(255,69,0));
    mNotificationPaint.setAlpha(220);

    mTextPaint.setAntiAlias(true);
    mTextPaint.setColor(Color.BLACK);
    mTextPaint.setStyle(Style.FILL);
    mTextPaint.setTextSize(this.getWidth() / 3);
    mTextPaint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
    mTextPaint.setTextAlign(Align.CENTER);
    mTextPaint.setLinearText(true);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    int diameter = this.getWidth() / 3;

    /*
    canvas.drawCircle(
            this.getWidth() - diameter,
            this.getHeight() - diameter, 
            diameter,
            this.mNotificationPaint
        );
        */


    //Get the text bounds.
    Rect foundBounds = new Rect();
    mTextPaint.getTextBounds("1", 0, "1".length(), foundBounds);
    foundBounds.offset(0, diameter);

    canvas.drawText(
            //String.valueOf(mNumberOfNotifications), 
            "1",
            0,
            foundBounds.bottom,
            this.mTextPaint
        );

    //For testing the location of the text bounds.
    canvas.drawRect(foundBounds, mNotificationPaint);

}

}

1 个答案:

答案 0 :(得分:1)

您在this.getWidth()中获得onAttachedToWindow() 0,因此文字大小设置为0.

但您在this.getWidth()中获得onDraw值,因此在onDraw中添加此行

mTextPaint.setTextSize(this.getWidth() / 3);