2013-09-24 177 views
15

我有一個Android應用程序,其中我有幾個圖像在資產文件夾中。現在我想製作一組這樣的圖像。現在,我的問題是: - 當我們的圖像是繪製我們可以作出一個數組一樣從資產文件夾加載圖片

int x[] = { 
    R.drawable.ss, 
    R.drawable.aa, R.drawable.sk, 
    R.drawable.xx 
}; 

等。當我的圖像位於資產文件夾中時,如何製作與上述圖像相同的數組。 我想在課堂上做一個數組。

+0

你可以用文件名的String數組 – JRowan

+0

使用搜索http://stackoverflow.com/questions/7645268/how-to-做從資產中加載圖像 – Lebedevsd

回答

25

你必須通過圖像像下面讀取圖片:

您可以使用AssetManager使用其open()方法來獲取InputStream和再使用decodeStream BitmapFactory()方法來獲取位圖。

private Bitmap getBitmapFromAsset(String strName) 
    { 
     AssetManager assetManager = getAssets(); 
     InputStream istr = null; 
     try { 
      istr = assetManager.open(strName); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     Bitmap bitmap = BitmapFactory.decodeStream(istr); 
     return bitmap; 
    } 
6

如果您的圖片存儲的圖像文件夾中的資產目錄,然後你可以得到圖像的列表作爲方式

private List<String> getImage(Context context) throws IOException { 
     AssetManager assetManager = context.getAssets(); 
     String[] files = assetManager.list("image"); 
     List<String> it = Arrays.asList(files); 
     return it; 
} 
+0

我想在課堂級別聲明它。這是可能的 – suneel

+0

然後你需要先獲得上下文然後你可以得到資產 –

+0

你能解釋更多的例子 – suneel

0

您有關於繪圖資源和資產產生錯誤的意思。你可以創建數組「odable」,因爲所有的drawable在R中都有自己的id(比如R.dawable.ss),所以如果你有合適的上下文,你可以使用指定的整數來繪製。

管理像圖像這樣的文件的其他方式是assests。如果你想通過他們的ID管理圖像,你必須添加這些圖像做drawables。換句話說,assert文件必須像dir中的簡單文件那樣進行管理。

您必須從資產AssetManager am=this.getAssets();獲取文件,然後準備要讀取/寫入的文件。如果你有圖像,你可以做這樣的事情:

try {  
    Bitmap bmp=BitmapFactory.decodeStream(am.open("009.gif")); 
    imageView.setImageBitmap(bmp); 

} catch (IOException e) { 
    e.printStackTrace(); 
} 
4
// load image from asset folder 
     try { 
      // get input stream 
      InputStream ims = getAssets().open("avatar.jpg"); 
      // load image as Drawable 
      Drawable d = Drawable.createFromStream(ims, null); 
      // set image to ImageView 
      mImage.setImageDrawable(d); 
     } 
     catch(IOException ex) { 
      return; 
     } 

    or you can create drawable array 
    Drawable d []={d}; 
相關問題