我想要读取drawable文件夹中的位图并将其存储为Bitmap变量,以便我可以将其设置为背景。最好的方法是使用“文件阅读器”吗?例如
Bitmap decodeFile (String pathName) method
还有没有一种方法可以这样设置:
Bitmap bmp = R.drawable."bitmapFileName";
我已经尝试过这个方法,但它返回的是一个整数,我只是想知道我是否正确理解了。
非常感谢任何帮助 :)
R.drawable."bitmapFileName"
实际上只是一个整数,因为它是您项目的R类中的索引(静态整数)(请参见此处)。您可以像这样从资源文件夹加载位图:
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.yourBitmap);
我在Android开发社区找到了这段代码。
InputStream is = parentActivity.getResources().getAssets().open(iconFile);
Bitmap bmp = BitmapFactory.decodeStream(is);
BitmapDrawable bitmapDrawable = new BitmapDrawable(is);
那么只需要使用 yourView.setBackgroundDrawable(bitmapDrawable);
即可。
public Drawable getImageByName(String nameOfTheDrawable, Activity a){
Drawable drawFromPath;
int path = a.getResources().getIdentifier(nameOfTheDrawable,
"drawable", "com.mycompany.myapp");
Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap source = BitmapFactory.decodeResource(a.getResources(), path, options);
drawFromPath = new BitmapDrawable(source);
return drawFromPath;
}
当然,你可以返回位图而不是可绘制对象。
Drawable d = getImageByName("mageFileName", this);
/*
* You can get Bitmap from drawable resource id in the following way
*/
BitmapDrawable drawable = (BitmapDrawable)context.getResources()
.getDrawable(drawableId);
bitmap = drawable.getBitmap();