Android:如何移动位图?
我想将位图“移动”一定的 x 和 y 偏移量。通过移位,我的意思是,如果我有一个 300x500 位图,并且我将其移动 -50 的 ay 偏移量,我希望每个像素向上移动 50 个像素,并且沿位图底部的 300x50 像素矩形为空白。如果 shiftX 和 shiftY 为负值,下面的代码可以很好地工作,但对于正值则根本不起作用。我不知道为什么?
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);
我已经尝试过很多不同的版本。似乎尝试使用正 y 转换位图总是会产生垃圾。在这个更简单的示例中,负的shiftY给出了预期的行为,但是正的shiftY给出了垃圾结果:
Canvas bitmapCanvas = new Canvas(mBitmap);
bitmapCanvas.drawBitmap(mBitmap, 0, shiftY, null);
*更新。这是通过下面的代码解决的。然而,这并不是内存高效的。对于更好的解决方案有什么建议吗?
Canvas bitmapCanvas = new Canvas(mBitmap);
Bitmap tempBitmap = mBitmap.copy(CONFIG.ARGB_8888, false);
bitmapCanvas.drawBitmap(tempBitmap, 0, shiftY, null);
I would like to "shift" a Bitmap by a certain x and y offset. By shift, I mean, If I have a 300x500 bitmap, and I shift it by a y offset of -50, I would expect every pixel to move up 50 pixels, and a 300x50 pixel rectangle to be blank, along the bottom of the Bitmap. The below code works great if shiftX and shiftY are negative, but doesn'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've tried many different versions of this. It seems that trying to translate a Bitmap with a positive y always produces garbage. In this simpler example, a negative shiftY gives expected behavior, but a positive shiftY gives a garbage result:
Canvas bitmapCanvas = new Canvas(mBitmap);
bitmapCanvas.drawBitmap(mBitmap, 0, shiftY, null);
*Update. This is solved by the below code. However, this is not memory efficient. Any suggestions for a better solution?
Canvas bitmapCanvas = new Canvas(mBitmap);
Bitmap tempBitmap = mBitmap.copy(CONFIG.ARGB_8888, false);
bitmapCanvas.drawBitmap(tempBitmap, 0, shiftY, null);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我无法用你的代码重现这个。
我已经尝试过使用 50 和 -50 的偏移量,两者都按预期工作。
我的代码里面的绘图方法:
或者用正数:
I can't reproduce this with your code.
I have tried it with an offset of 50 and -50 and both works as expected.
My code inside the drawing method:
or with positive:
简单的解决方案...
Simple solution ...