在 Canvas 中居中 public void onDraw(Canvas canvas) 内的缩放位图
Center in Canvas an scaled Bitmap inside public void onDraw(Canvas canvas)
我设法缩放了位图。
Rect src = new Rect(0, 0, icon.getWidth() - 1, icon.getHeight() - 1);
Rect dest = new Rect(0,0,Math.round(newWidth), Math.round(newHeight));
canvas.drawBitmap(icon, src, dest, null);
问题是图像出现在 canvas 的左侧。
我希望它位于 canvas 的中间。
一个大问题是我担心内存 management.So 我不想预先创建缩放位图,我更愿意使用动态创建和绘制缩放位图的方法:
canvas.drawBitmap(icon, src, dest, null);
我该如何执行?
如果你想让图像以Canvas
为中心,很简单,只需计算中心坐标并将其应用到dest
。
int cx = (getWidth() - newWidth) / 2;
int cy = (getHeight() - newHeight) / 2;
Rect src = new Rect(0, 0, myBitmap.getWidth() - 1, myBitmap.getHeight() - 1);
Rect dest = new Rect(cx, cy, cx+Math.round(newWidth), cy+Math.round(newHeight));
canvas.drawBitmap(myBitmap, src, dest, null);
但是,这不是正确的方法,因为每次调用 onDraw(Canvas)
时都会创建 2 Rect
。只要 gc 垃圾回收它,它就会保留在内存中。
为避免这种情况,您可以预先计算 Rect
并存储它们,因为它们在内存中不像位图那么重。
我设法缩放了位图。
Rect src = new Rect(0, 0, icon.getWidth() - 1, icon.getHeight() - 1);
Rect dest = new Rect(0,0,Math.round(newWidth), Math.round(newHeight));
canvas.drawBitmap(icon, src, dest, null);
问题是图像出现在 canvas 的左侧。 我希望它位于 canvas 的中间。 一个大问题是我担心内存 management.So 我不想预先创建缩放位图,我更愿意使用动态创建和绘制缩放位图的方法:
canvas.drawBitmap(icon, src, dest, null);
我该如何执行?
如果你想让图像以Canvas
为中心,很简单,只需计算中心坐标并将其应用到dest
。
int cx = (getWidth() - newWidth) / 2;
int cy = (getHeight() - newHeight) / 2;
Rect src = new Rect(0, 0, myBitmap.getWidth() - 1, myBitmap.getHeight() - 1);
Rect dest = new Rect(cx, cy, cx+Math.round(newWidth), cy+Math.round(newHeight));
canvas.drawBitmap(myBitmap, src, dest, null);
但是,这不是正确的方法,因为每次调用 onDraw(Canvas)
时都会创建 2 Rect
。只要 gc 垃圾回收它,它就会保留在内存中。
为避免这种情况,您可以预先计算 Rect
并存储它们,因为它们在内存中不像位图那么重。