Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object allocation during draw/layout?

Tags:

java

android

I get 3 warning for object allocation during draw/layout

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);

I get an error on new Rect(); and on both new Paint();

The exact error is avoid object allocation during draw/layout operations (prelocate and reuse instead)

like image 852
lramos15 Avatar asked May 09 '13 22:05

lramos15


1 Answers

Well, your 'error' points to exact problem. onDraw() method is called by OS many-many times, thus allocating something within this function is extremely bad idea. You need to allocate your Rect and Paint beforehand and just use them within 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);
    }
}
like image 86
Pavel Dudka Avatar answered Nov 11 '22 08:11

Pavel Dudka