从存储在drawable文件夹中的位图获取位图信息

时间:2011-08-30 11:14:28

标签: android file bitmap drawable

我想在我的drawable文件夹中读取一个位图并将其存储为Bitmap变量,以便我可以将其设置为背景。最好的方法是使用“文件阅读器”吗?喜欢

  Bitmap decodeFile (String pathName) method

或者有没有办法像这样设置它:

  Bitmap bmp = R.drawable."bitmapFileName"; 

(我试过这个但是返回一个int,只是想知道我是否在正确的轨道上)

任何帮助都会很棒:)

4 个答案:

答案 0 :(得分:31)

R.drawable."bitmapFileName"实际上只是一个整数,因为它是项目R类的索引(静态整数)(参见更多here)。您可以从资源的文件夹加载位图,如下所示:

Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.yourBitmap);

我在Android Development Community找到了这段代码。

答案 1 :(得分:6)

我通常使用资产文件夹

InputStream is = parentActivity.getResources().getAssets().open(iconFile);
Bitmap bmp = BitmapFactory.decodeStream(is);
BitmapDrawable bitmapDrawable = new BitmapDrawable(is);

然后只是yourView.setBackgroundDrawable(bitmapDrawable);

答案 2 :(得分:4)

可以按名称加载drawable或bitmap。这是一个例子:

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;
}

您当然可以返回Bitmap而不是drawable。

  

Drawbale d = getImageByName(“mageFileName”,this);

答案 3 :(得分:0)

/*
 * You can get Bitmap from drawable resource id in the following way
 */
BitmapDrawable drawable = (BitmapDrawable)context.getResources()
        .getDrawable(drawableId);
bitmap = drawable.getBitmap();