2013-09-26 26 views
2

我想在我的android應用程序中設置一個可變位圖中不同顏色的像素區域。不幸的是,我無法讓setPixels()正常工作。我不斷得到ArrayOutOfBoundsExceptions。我認爲這可能與邁步有點關係,但我真的不確定。這是我仍然不明白的唯一參數。我在setPixels(不是setPixel)上看到的唯一其他帖子在這裏:drawBitmap() and setPixels(): what's the stride?它並沒有幫助我。我嘗試將步幅設置爲0,作爲位圖的寬度,作爲位圖的寬度 - 我試圖繪製的區域,它仍然崩潰。這是我的代碼:Android的SetPixels()解釋和例子?

public void updateBitmap(byte[] buf, int offset, int x, int y, int width, int height) { 
    // transform byte[] to int[] 
    IntBuffer intBuf = ByteBuffer.wrap(buf).asIntBuffer(); 
    int[] intarray = new int[intBuf.remaining()]; 
    intBuf.get(intarray);          

    int stride = ?????? 
    screenBitmap.setPixels(intarray, offset, stride, x, y, width, height); // crash here 

我的位圖是可變的,所以我知道這不是問題。我也確定我的字節數組正在被正確地轉換爲整數數組。但我不斷收到ArrayOutOfBoundsExceptions,我不明白爲什麼。請幫我算出這個

編輯 - 這裏是我構建了假輸入:

int width = 1300; 
int height = 700; 
byte[] buf = new byte[width * height * 4 * 4]; // adding another * 4 here seems to work... why?  
for (int i = 0; i < width * height * 4 * 4; i+=4) { 
    buf[i] = (byte)255; 
    buf[i + 1] = 3; 
    buf[i + 2] = (byte)255; 
    buf[i + 3] = 3;   
} 
//(byte[] buf, int offset, int x, int y, int width, int height) - for reference   
siv.updateBitmap(buf, 0, 0, 0, width, height); 

所以寬度和高度都是整數(至少應該是)的正確的金額。

EDIT2 - 這裏是獨創screenBitmap的代碼:

public Bitmap createABitmap() { 
int w = 1366; 
int h = 766; 

byte[] buf = new byte[h * w * 4]; 

for (int i = 0; i < h * w * 4;i+=4) { 
     buf[i] = (byte)255; 
    buf[i+1] = (byte)255; 
    buf[i+2] = 0; 
    buf[i+3] = 0; 
} 

DisplayMetrics metrics = new DisplayMetrics(); 
getWindowManager().getDefaultDisplay().getMetrics(metrics); 

IntBuffer intBuf = ByteBuffer.wrap(buf).asIntBuffer(); 
int[] intarray = new int[intBuf.remaining()]; 
intBuf.get(intarray);           

Bitmap bmp = Bitmap.createBitmap(metrics, w, h, itmap.Config.valueOf("ARGB_8888")); 
bmp.setPixels(intarray, 0, w, 0, 0, w, h); 
return bmp; 
} 

似乎在這種情況下工作,不知道有什麼區別

+0

步幅應爲寬度。這是1d數組中的數量,當它假裝爲2d數組時,您需要向下移動1。 – Tatarize

+0

這不起作用,因爲setPixels()需要intarray。期。你的4色樣本字節數組變成了各種不同的藍色。 0baaaaaaaarrrrrrrrggggggggbbbbbbbbb – Tatarize

回答

0

如果你想借鑑位圖,你最好的辦法是放棄這種方法,而改用帆布:

Canvas canvas = new Canvas(screenBitmap); 

然後,您可以繪製特定點(如果你想畫一個像素),或其它形狀就像矩形,圓形等:

canvas.drawPoint(x, y, paint); 

希望這有助於。

+0

嗯,我沒有試圖在位圖上畫畫。我試圖模擬一個實時視頻源,所以我將在新圖像數據進入時更新位圖。所以我不想繪製,我想將像素設置爲新值 – Trevor

2

或許應該是:

screenBitmap.setPixels(intarray, 0, width/4, x, y, width/4, height); 

因爲你轉換字節爲int。你的錯誤是ArrayOutOfBoundsExceptions。檢查尺寸是否爲intBuf.remaining() = width * height/4

+0

我的數組我認爲大小是正確的。如果我創建一個1300 x 700字節輸入的假輸入(因此1300 x 700 x 4字節= 3,640,000),則會創建長度爲91,000的intarray,這是總數的四分之一。在ARGB_8888格式中,每個像素是一個32位int,所以91,000 = 1300 x 700,因此應該有足夠的像素數據填充位圖的1300x700部分。但是,當我做1300 x 700 x 4 x 4像素時,它會填充適當的空間而不會崩潰。不知何故,我的數學錯了嗎? -EDIT:參見上面關於如何構建假輸入 – Trevor

+0

哪些行代碼崩潰?intBuf.remaining()或screenBitmap.setPixels?你的跨步價值是什麼?它無法顯示 – yushulx

+0

做的寬度和高度值等於screenBitmap的大小? – yushulx