Android: how to move a bitmap?

I would like to “shift” the bitmap by a specific offset x and y. By shift, I mean, if I have a 300 x 500 bitmap, and I shift it with a -50 offset, I expect each pixel to move 50 pixels, and a 300 × 50 pixel rectangle will be empty , at the bottom of the bitmap, The code below works fine if shiftX and shiftY are negative, but don't work at all for positive values. I have no idea why?

Rect srcRect = new Rect(-shiftX, -shiftY, mBitmap.getWidth(), mBitmap.getHeight());
Rect destRect = new Rect(srcRect);
destRect.offset(shiftX, shiftY);

Canvas bitmapCanvas = new Canvas(mBitmap);
bitmapCanvas.drawBitmap(mBitmap, srcRect, destRect, null);

I have tried many different versions of this. It seems that trying to translate a bitmap with positive y always produces garbage. In this simpler example, a negative shift of Y gives the expected behavior, but a positive shift of Y gives the result of garbage:

 Canvas bitmapCanvas = new Canvas(mBitmap);
 bitmapCanvas.drawBitmap(mBitmap, 0, shiftY, null);

* Update. . . ?

Canvas bitmapCanvas = new Canvas(mBitmap);
Bitmap tempBitmap = mBitmap.copy(CONFIG.ARGB_8888, false);
bitmapCanvas.drawBitmap(tempBitmap, 0, shiftY, null);
+3
2

. 50 -50, .

:

// negative value: -50
Rect srcRect = new Rect(-(-50), -(-50), mBitmap.getWidth(), mBitmap.getHeight());
Rect destRect = new Rect(srcRect);
destRect.offset(-50, -50);

canvas.drawBitmap(mBitmap, srcRect, destRect, null);

:

// positive value: 50
Rect srcRect = new Rect(-50, -50, mBitmap.getWidth(), mBitmap.getHeight());
Rect destRect = new Rect(srcRect);
destRect.offset(50, 50);

canvas.drawBitmap(mBitmap, srcRect, destRect, null);
0

...

canvas.translate(dx, dy);

canvas.draw....();
0

Source: https://habr.com/ru/post/1780249/


All Articles