gpt4 book ai didi

java - 绘制/布局期间的对象分配?

转载 作者:IT老高 更新时间:2023-10-28 23:32:47 28 4
gpt4 key购买 nike

我在绘制/布局期间收到 3 个对象分配警告

super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
Paint textPaint = new Paint();
textPaint.setARGB(50,100,100,250);
textPaint.setTextAlign(Align.CENTER);
textPaint.setTextSize(50);
textPaint.setTypeface(font);
canvas.drawText("Logan is awesom",canvas.getWidth()/2,200,textPaint);
canvas.drawBitmap(pBall, (canvas.getWidth()/2), changingY, null);
if (changingY <canvas.getHeight()){
changingY += 10;
}else{
changingY=0;
}
Rect middleRect = new Rect();
middleRect.set(0, 400, canvas.getWidth(), 550);
Paint ourBlue = new Paint();
ourBlue.setColor(Color.BLUE);
canvas.drawRect(middleRect, ourBlue);

我在 new Rect(); 上得到一个错误;和 new Paint();

确切的错误是在绘制/布局操作期间避免对象分配(而不是预先定位和重用)

最佳答案

好吧,您的“错误”指向确切的问题。 onDraw() 方法被操作系统多次调用,因此在这个函数中分配一些东西是非常糟糕的主意。您需要预先分配您的 RectPaint 并在 onDraw

中使用它们
class YourClass extends View
{
Rect middleRect;
Paint ourBlue;
Paint textPaint;

public YourClass()
{
//constructor
init();
}

private void init()
{
middleRect = new Rect();
ourBlue; = new Paint();
textPaint = new Paint();

ourBlue.setColor(Color.BLUE);
textPaint.setARGB(50,100,100,250);
textPaint.setTextAlign(Align.CENTER);
textPaint.setTextSize(50);
textPaint.setTypeface(font);
}

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

canvas.drawText("Logan is awesom",canvas.getWidth()/2,200,textPaint);
canvas.drawBitmap(pBall, (canvas.getWidth()/2), changingY, null);
if (changingY <canvas.getHeight()){
changingY += 10;
}else{
changingY=0;
}

//if canvas size doesn't change - this can be moved to init() as well
middleRect.set(0, 400, canvas.getWidth(), 550);

canvas.drawRect(middleRect, ourBlue);
}
}

关于java - 绘制/布局期间的对象分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16472529/

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