Andy T
Andy T

Reputation: 9881

Determining path to read a picture from Resources in mono for android

I am trying to read a picture by passing in the file location. I know I can get the picture from the resources/drawable directory by Resource.Id. However, I will have quiet a bit pictures, so rather than doing a large switch-statement (and getting the right one), I would like to read the picture by name.

In the code below, I am trying to read a logo.png file from the Drawable directory. I am not sure if this is the correct directory where I should be placing the picture, or if I should be putting it in another directory (assets??).

I believe the code is correct, and my problem is the file path. I can't figure out what the format of the file path should be.

var imageView = FindViewById<ImageView>(Resource.Id.test_image);
var file = new Java.IO.File("Resources/Drawable/logo.png");
var drawableLogo = Android.Graphics.Drawables.Drawable.CreateFromPath(file.AbsolutePath);
imageView.SetImageDrawable(drawableLogo);

To answer my own question...

Looks like I was suppose to put the picture in the Assets folder (With a Build Action of "AndroidAsset")

Then to read it, I just use the Open method of off Assets:

var imageView = FindViewById<ImageView>(Resource.Id.test_image);
var inputStream = Assets.Open("logo.png");
var bMap = BitmapFactory.DecodeStream(inputStream);
imageView.SetImageBitmap(bMap);

Upvotes: 1

Views: 2414

Answers (2)

Greg Shackles
Greg Shackles

Reputation: 10139

One option is to look up a resource by its name:

int id = Resources.GetIdentifier("drawable/icon", null, PackageName);
imageView.SetImageResource(id);

This isn't really a great solution, though. For one, it will be slower than accessing a resource directly by its identifier. Also, you will need to use the Java version of the resource name (for example, Icon gets translated to icon). In general I wouldn't recommend doing this.

A better option is to keep all of the images as assets, setting their BuildAction to AndroidAsset. Then you can do something like this:

var drawable = Drawable.CreateFromStream(Assets.Open("Icon.png", Access.Streaming), null);
imageView.SetImageDrawable(drawable);

Upvotes: 4

jpobst
jpobst

Reputation: 9982

You probably want to use the Context.Resources property, assuming you are in an Activity or something:

var logo = Resources.GetDrawable (Resource.Drawable.Logo)

This way you don't have to worry about where the image is actually stored.

Upvotes: 1

Related Questions