9
votes

This is my page in portable project

    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:b="clr-namespace:Corcav.Behaviors;assembly=Corcav.Behaviors"
                 xmlns:local="clr-namespace:MyMobileApp;assembly=MyMobileApp"
                 x:Class="MyMobileApp.MainPage"
                 x:Name="MainPage">

      <Image Source="{local:ImageResource myimage.jpg}" />

This is my ImageResourceExtension in same portable project

namespace MyMobileApp
{
    [ContentProperty("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;
        }
    }
}

I have tried to add myimage.jpg as embedded in root of my project and in Resources folder, but no image is shown.

While debugging I see that the returned imageSource is of type Xamarin.Forms.StreamImageSource. How do I check if this is really found?

Can anyone spot the error here?

4

4 Answers

13
votes

The correct XAML was to add the app name to the source.

<Image Source="{local:ImageResource MyMobileApp.myimage.jpg}" />
9
votes

By default the image will have Build Action: None; this needs to be set to Build Action: EmbeddedResource. Right click on Image > properties > set [Build Action: EmbeddedResource] [enter image description here]1

0
votes

Can you explain the intent of the extension a bit more? Assuming you are putting your images in the proper folders ('Resources' on iOS, 'Resources/Drawable' on Android), then all you need in your XAML is just:

<Image Source="FeaturedAreaMockup.jpg" />

That will find the images in the appropriate folder and show them - why aren't you just doing that? What's the point of the extension?

0
votes

To read assets/resources folder you need to use:

ImageSource.FromFile("myimage.jpg");'

ImageSource.FromResource uses images included as EmbeddedResource

More here: https://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/images/