I wanna read in a bitmap that I have in my drawable folder and store it as a Bitmap variable so that I can set it as a background. Would the best way to do this be using a "file reader"? like
Bitmap decodeFile (String pathName) method
Or is there a way to just set it like this:
Bitmap bmp = R.drawable."bitmapFileName";
(I have tried this but returns an int, just wondering if I was on the right track)
Any help would be great :)
A Bitmap is a representation of a bitmap image (something like java. awt. Image). A Drawable is an abstraction of "something that can be drawn".
A bitmap is simply a rectangle of pixels. Each pixel can be set to a given color but exactly what color depends on the type of the pixel. The first two parameters give the width and the height in pixels. The third parameter specifies the type of pixel you want to use.
The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.
The R.drawable."bitmapFileName"
is, indeed, just an integer, for it is an index (static integer) at your project's R class (see more here). You can load your bitmap from the resources's folder like this:
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.yourBitmap);
I found this code at the Android Development Community.
I usually use the assets folder
InputStream is = parentActivity.getResources().getAssets().open(iconFile);
Bitmap bmp = BitmapFactory.decodeStream(is);
BitmapDrawable bitmapDrawable = new BitmapDrawable(is);
then just yourView.setBackgroundDrawable(bitmapDrawable);
It is possible to load a drawable or bitmap by name. Here is an example:
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;
}
You can of course return Bitmap instead a drawable.
Drawbale d = getImageByName("mageFileName", this);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With