Reputation: 57
I am able to display image from Drawable folder by using
<image source="live.png"/>
But i don't know how to get image from other folder i create in Resource Can somebody help me?
Upvotes: 1
Views: 1298
Reputation: 1582
Android is very picky about where you can put images, so your best bet is to store your images in the common project. In this example I assume a standard Xamarin.Forms solution with the following projects: Foo, Foo.Android, Foo.IOS and Foo.UWP. Yours will obviously have different names, so you'll have to substitute the Foos...
All the following code will go into the common code project, Foo
.
First, create a new folder called Extensions
(just to keep your code tidy) and add the following class to it:
[ContentProperty(nameof(Source))]
public class ImageResourceExtension : IMarkupExtension
{
public string Source { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
if (Source == null)
{
return null;
}
var imageSource = ImageSource.FromResource(Source);
return imageSource;
}
}
Now add the namespace for this class to your markup:
xmlns:extensions="clr-namespace:Foo.Extensions"
Next, create a folder for your images, again in your common project, NOT in your Android project. You can create subfolders as well. Add your images and make sure that the build action for each image is set to Embedded Resource
.
Now you can reference those images in your XAML like this:
<Image Source="{extensions:ImageResource Foo.Images.Subfolder.Bar.png}">
Note that you need to supply the full path of the image, including the project name (Foo in this case) and that folders are separated by dots, not slashes.
Upvotes: 1