gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:53:50 25 4
gpt4 key购买 nike

我正在尝试在以图像为背景的自定义 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com