2013-02-04 35 views
0

我想創建一個可以在畫布上繪製的圖像數組。這是我有:在畫布上創建一個圖像數組

List<Integer> imageHolder = new ArrayList<Integer>(); 
imageHolder.add((int)R.drawable.bus_1); 
imageHolder.add((int)R.drawable.bus_2); 
imageHolder.add((int)R.drawable.bus_3); 

然後我試着從我的onDraw方法訪問這樣的圖片:

protected void onDraw(Canvas canvas) { 
     canvas.drawColor(Color.BLACK); 


     for (int i = 0; i < imageHolder.size(); i++){ 


      canvas.drawBitmap(imageHolder.get(i), 0, 0, null); 
     } 


    } 

但我得到一個錯誤,說我的論據並不適用於我的畫布。 drawbitmap。有誰知道如何做到這一點?我一直在尋找解釋如何做到這一點,我無法找到任何地方。

編輯:這是我如何得到它的工作,打印出3張圖像在不同的點在屏幕上:

for (int i = 0; i < imageHolder.size(); i++) { 
    bMap = BitmapFactory.decodeResource(res, imageHolder.get(0)); 
    canvas.drawBitmap(bMap, 100, 100, null); 
    bMap2 = BitmapFactory.decodeResource(res, imageHolder.get(1)); 
    canvas.drawBitmap(bMap2, 500, 100, null); 
    bMap3 = BitmapFactory.decodeResource(res, imageHolder.get(2)); 
    canvas.drawBitmap(bMap3, 900, 100, null); 
     } 

回答

1

你做的是你最初添加一堆整數到一個ArrayList,然後你通過這個ArrayList的嘗試循環並繪製一個位圖,使用標識的資源這個整數。問題在於Canvas類中的drawBitmap方法的第一個參數必須是顏色的整數數組或Bitmap資源。不只是一個整數,指向一個。欲瞭解更多信息,請致電check the documentation

爲了通過ID獲取特定的資源作爲位圖,你需要這樣做:

Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.your_drawable_id); 

或者在你的情況你的循環需要看起來像這樣:

Resources res = getResources(); // Cache them 
Bitmap bMap; 
for (int i = 0; i < imageHolder.size(); i++){ 
    bMap = BitmapFactory.decodeResource(res, imageHolder.get(i)); 
    canvas.drawBitmap(bMap, 0, 0, null); 
} 
+0

輝煌,這是什麼我正在尋找。謝謝。是否有一種方法可以改變每個圖像在屏幕上的繪製位置,因爲它們都是在0,0點繪製的。 – DMC

+0

請看看我在答覆中提供的文檔鏈接。它詳細解釋了'drawBitmap'可以使用哪些參數,包括Rect對象,X/Y座標,Mesh等。 –

+0

謝謝我在上面的編輯中看到了它。 – DMC

0

大聲笑!檢查canvas.drawBitmap第一個參數是一個Bitmap對象,而您只有指向該資源的整數。

您可以使用:

canvas.drawBitmap(BitmapFactory.decodeResource(getContext().getResources(), imageHolder.get(i)), 0, 0, null);