2011-04-18 71 views
9

在自定義視圖上使用9修補圖像資源的正確方法是什麼?使用時使用drawBitmap在畫布上繪製9修補圖像

fundo_bookshelf

但是:

我這樣做:

background = BitmapFactory.decodeResource(getResources(), R.drawable.fundo_bookshelf); 
canvas.drawBitmap(background, null, new Rect(0, y, width, y+backgroundHeight), null); 

fundo_bookshelf是正確的9補丁圖像,保存爲fundo_bookshelf.9.png,如下圖所示drawBitmap,整個圖像被拉伸,而不是隻有頂部有黑色像素的部分,如此截圖所示: strechted image

回答

23

這樣的事情?

NinePatchDrawable bg = (NinePatchDrawable) resources.getDrawable(id); 
if (bg != null) { 
    bg.setBounds(0, 0, getWidth(), getHeight()); 
    bg.draw(canvas); 
    } 

(抱歉,我沒有把它適應你的代碼,也就是從我自己的直剪切/粘貼,但希望足以去)

+0

它的工作奇妙!非常感謝 – 2011-04-19 14:17:30

+2

如果有人犯我同樣的錯誤,'setBounds'部分是非常重要的。 – Arnaud 2012-10-22 20:43:28