2016-07-05 47 views
1

我在java中爲android設備編寫了一個代碼,合併一些png圖像並創建一個位圖並在Imageview中顯示。它的工作原理,但之後,應用程序將太慢。我的代碼有什麼問題?我認爲這有點像內存泄漏!這樣對嗎?以及如何修復代碼?合併幾個圖像使android非常慢

public Drawable merge(Drawable a, String uri){ 
     Drawable[] layers = new Drawable[2]; 
     layers[0] = a; 
     int imageResource = getResources().getIdentifier(uri, null, getPackageName()); 
     layers[1] = getResources().getDrawable(imageResource); 
     LayerDrawable layerDrawable = new LayerDrawable(layers);   
     return layerDrawable.mutate(); 

    } 

public void ShowImage(ArrayList<String> states) { 

     img1.setImageDrawable(null); 

     Drawable map = getResources().getDrawable(R.drawable.emptymap); 

     int i = 1; 
     for (String state : states) { 
      String layerName = state; 

      String uri = "drawable/"+layerName; 
      try { 
       map = merge(map ,uri); 
      } 
      catch(Exception e){} 
     } 

     img1.setImageDrawable(map); 
} 
+1

提示:**從不**與空的catch塊。完全忽略錯誤是一個超級壞主意! – GhostCat

回答

0

LayerDrawable可以作爲多個高分辨率PNG繪項目,因爲它在它的平局繪製一個層一個()函數很慢:

@Override 
    public void draw(Canvas canvas) { 
     final ChildDrawable[] array = mLayerState.mChildren; 
     final int N = mLayerState.mNumChildren; 
     for (int i = 0; i < N; i++) { 
      final Drawable dr = array[i].mDrawable; 
      if (dr != null) { 
       dr.draw(canvas); 
      } 
     } 
    } 

這將是更好的緩存LayerDrawable的排放轉換成位圖,然後使用這個位圖。

Bitmap bmp = Bitmap.createBitmap(layeredDrawable.getIntrinsicWidth(), 
layeredDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); 
layeredDrawable.setBounds(0, 0, layeredDrawable.getIntrinsicWidth(), layeredDrawable.getIntrinsicHeight()); 
layerDrawable.draw(new Canvas(bmp)); 

另一件要檢查的是從資源中加載它們後的png drawables大小。如果放置在錯誤的資源文件夾中,它們可能會太大(例如,加載密度= 3屏幕後位於繪圖/文件夾中的500x500 png將構成1500x1500)。