Search code examples
javaandroidandroid-studioandroid-viewondraw

RectF goes out of borders on Canvas


I'm improving a simple Android game called Arkanoid, where I'm having a small problem drawing a RectF on a Canvas.

I implemented a power-up option where, if you take this power-up, the Paddle streches from a 200x Paddle to a 500x Paddle.

    private RectF r;
    private Paint paint = new Paint();
    private Bitmap flipperBit;

    // Draw Paddle
    flipperBit = BitmapFactory.decodeResource(getResources(), R.drawable.flipper);
    paint.setColor(Color.WHITE);

    if (powerUpTaken) {
        r = new RectF(flipper.getX(), flipper.getY(), flipper.getX() + 500, flipper.getY() + 40);
    } else {
        r = new RectF(flipper.getX(), flipper.getY(), flipper.getX() + 200, flipper.getY() + 40);
    }
    canvas.drawBitmap(flipperBit, null, r, paint);

The main problem is that when I hit the powerup, the Paddle successfully streches from 200 to 500, but goes out of border as in the gif below, thinking it's still a 200x Paddle. Please note that all of this , it's written inside the onDraw overrided-function.

I know, I need to implement a way to stretch the Paddle for x seconds, but as of now I want to make it work first.

Any suggestion would be really appreciated. :)

1.st


Solution

  •   //set to ZERO if not needed
    final cMargin = 10;
    int cPaddingWidth;
    final int cPaddingHeight = 40;
    final RectF cRectF = new RectF();
    if (powerUpTaken) cPaddingWidth = 500;
    else cPaddingWidth = 200;
    cRectF.left = Math.max(cMargin, flipper.getX());
    cRectF.right = cRect.left + cPaddingWidth;
    if (cRectF.right > (this.getWidth() - cMargin)) {
        cRectF.left = (this.getWidth() - cMargin) - cPaddingWidth;
        cRectF.right = cRectF.left + cPaddingWidth;
    }
    cRectF.top = Math.max(0, flipper.getY());
    cRectF.bottom = cRect.top + cPaddingHeight;
    r.set(cRectF);