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

前端之家收集整理的这篇文章主要介绍了java – 绘制/布局期间的对象分配?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在绘制/布局期间得到3个对象分配的警告
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
Paint textPaint = new Paint();
textPaint.setARGB(50,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);

我得到一个新的Rect()的错误;
并在两个新的Paint();

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

解决方法

那么你的’错误’指出了确切的问题. onDraw()方法被OS多次调用,因此在这个函数内分配的东西是非常糟糕的主意.
您需要事先分配您的Rect和Paint,并在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,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",textPaint);
        canvas.drawBitmap(pBall,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,550);

        canvas.drawRect(middleRect,ourBlue);
    }
}
原文链接:https://www.f2er.com/java/121747.html

猜你在找的Java相关文章