2011-03-06 41 views
2

可以从资源传递给R.的图像加载一个String。可以从传递String参数的资源加载R.drawable?

我想这一点:

public static Bitmap LoadBitmap(Context context, String filename) 
{ 
    Bitmap image; 
    image = BitmapFactory.decodeResource(context.getResources(), R.drawable.filename); 
    return image; 
} 

抛出以下错误:

filename cannot be resolved or is not a field 

我试图创建R档creatic恒定的场,而抛出下面一行:

R.java was modified manually! Reverting to generated version! 

我会感谢您的帮助或建议。谢谢

回答

9

资源可以作为原始数据访问:使用AssetManager.open(..)。只需传递想要的位图的文件名(例如“drawable/myimage.png”)即可。

然后您可以使用BitmapFactory.decodeStream(..)从数据流创建位图。

更新:

public static Bitmap LoadBitmap(Context context, String filename){ 
    AssetManager assets = context.getResources().getAssets(); 
    InputStream buf = new BufferedInputStream((assets.open("drawable/myimage.png"))); 
    Bitmap bitmap = BitmapFactory.decodeStream(buf); 
    // Drawable d = new BitmapDrawable(bitmap); 
    return bitmap; 
} 
+0

你能不能举个例子吗?我可以用inputstream来做吗?谢谢 – karse23 2011-03-06 17:30:15

0

@Peter Knego(没有足够的声誉直接标注了答案 - 愚蠢的SO)

资产管理人的我(有限)的理解是,它允许访问foo/assets目录中的文件。因此,从彼得代码将访问:

foo/assets/drawable/myimage.png

我觉得@ karse23想知道他是否可以在res/drawable目录访问图片:

foo/res/drawable/myimage.png

你为什么要这么做?那么如果你想从应用程序也可以访问第三方应用程序的资源。理想情况下,您可以在拥有资源的应用程序中使用R(因此您可以在布局中使用该ID)并在第三方应用程序(无法访问R类)中使用名称。

我试图做到这一点,彼得的方法是在我的代码中引用资产目录(但我再次访问另一个包中的资产)。 (你可以通过记录assetManager.list("")返回的字符串来检查这一点)。

在支持彼得的医生说:

public final AssetManager getAssets() 
Retrieve underlying AssetManager storage for these resources. 

这似乎支持的行为彼得建议(也许在旧的Android我使用???一个bug)。

最后,我认为解决的办法是重击文件在资产目录和代码访问它们的父应用程序:((或做Android的帅哥使用ContentProvider的意图的方式)。

相关问题