android - 在自定义 View 中绘制文本,canvas.drawText 不会显示

标签 android view

我正在尝试在以图像为背景的自定义 View 中绘制文本。正在绘制三样东西。

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

目前圆圈和位图绘制完美,但文本不显示。

自定义 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);

}

最佳答案

您在 onAttachedToWindow() 中获得 this.getWidth() 0,结果文本大小设置为 0。

但是你在 onDraw 中得到了 this.getWidth() 值,所以在 onDraw 中添加这一行

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

关于android - 在自定义 View 中绘制文本,canvas.drawText 不会显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23670507/

相关文章:

mysql - 插入 View 时的默认值

android - 将触摸事件传递到下方 View 取决于上方 View 触摸

MYSQL View 与选择性能和延迟

android - 我是 xamarin 新手,想在我的 xamarin.forms 项目中实现对话框

android - 如何在 android eclipse 中制作水平滑动日历?

java - 设置后退按钮无法使用波纹管代码?

android - 是否可以动态地将单选按钮转换为复选框?

java - 我是否需要创建工厂的测试版本以进行单元测试?

mysql - Laravel 5 选择查询将我的链接变成奇怪的格式

mysql - 创建基于多列值计算总值的 View 表