2012-05-18 45 views
0

我想通過下面的代碼旋轉Img(位圖)。它的工作精細到5-6輪,之後得到OME?在旋轉位圖時獲取OME

private void rotateImg() { 
    Matrix matrix = new Matrix(); 
    matrix.postScale(curScale, curScale); 
    matrix.postRotate(curRotate); 
    try { 
     temp = Bitmap.createBitmap(temp, 0, 0, temp.getWidth(), 
       temp.getHeight(), matrix, true); 
     setImage.setImageBitmap(temp); 
    } catch (OutOfMemoryError e) { 
     curRotate = curRotate - 45.0f; 
     Toast.makeText(this,"Out Of Memory",Toast.LENGTH_LONG).show(); 
    } 
} 

這裏「測試」是一個從SDCard加載的靜態位圖文件。

回答

1

爲什麼每次都創建位圖?有什麼具體原因嗎? 如果不是使用下面的代碼:

private void rotateImg() { 
    int cx = temp.getWidth()/2; 
    int cy = temp.getHeight()/2; 
    matrix.preTranslate(-cx, -cy); 
    matrix.postRotate(curRotate); 
    matrix.postTranslate(cx, cy); 
    setImage.setImageMatrix(matrix); 
} 
0

也許你每次調用此方法都必須使用bitmap.recycle()方法。嘗試這樣的,

private void rotateImg() { 
    Matrix matrix = new Matrix(); 
    matrix.postScale(curScale, curScale); 
    matrix.postRotate(curRotate); 
    try { 
     temp.recycle(); //removes the memory occupied by this bitmap object 
      temp=null; 
     temp = Bitmap.createBitmap(temp, 0, 0, temp.getWidth(), 
       temp.getHeight(), matrix, true); 
     setImage.setImageBitmap(temp); 
    } catch (OutOfMemoryError e) { 
     curRotate = curRotate - 45.0f; 
     Toast.makeText(this,"Out Of Memory",Toast.LENGTH_LONG).show(); 
    } 
} 
+0

但現在用在下一行「臨時」文件來創建一個新的位圖,我想我們可能會得到一些錯誤,此代碼「試圖使用回收的位圖」 – user1395885

+0

哦好的。你可以在setImage.setImageBitmap(temp)後添加這些行嗎?方法,並檢查。 –

1

第一個答案可能是一個可能的解決方案。這裏的問題是,你正在創建很多Bitmap對象的,這些對象相當大,並且不管出於什麼原因都沒有得到gc'd。

更好的解決方案可能是使用單個位圖,並在繪製時應用旋轉/縮放。例如,如果您正在使用屬於ViewCanvas,則rotateImg可以簡單地旋轉矩陣並在視圖上調用invalidate,然後在視圖的onDraw方法中使用畫布上的void drawBitmap (Bitmap bitmap, Matrix matrix, Paint paint)來渲染位圖。文檔是here