簡體   English   中英

畫布中心在public void onDraw(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.drawBitmap(icon, src, dest, null);

我該怎么做?

如果您希望圖像在Canvas上居中,只需dest坐標並將其應用於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並將它們存儲起來,因為它們不像內存上的Bitmap那么重。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM