Image not displaying in Xamarin forms using XAML?

Viewed 1970

I want to display an Image in my Xamarin forms project using XAML but is is not displaying. This is the code:

<Image x:Name="myimage" Source="logo.jpg"/>

I have set myimage's build action to embedded resource. I also tried this

<Image x:Name="myimage" Source="MyXamarinProject.logo.jpg"/>

Where MyXamarinProject is my namespace. But both not working. What is wrong here?

4 Answers

The recommended way to avoid decreasing application performance or problems displaying the images on different screen resolutions is adding each image on each platform specific folder:

  • Android: Project -> Resources -> Drawable (or each resolution drawable folder (-hdpi,-xhdpi...))

  • iOS: You can create an asset catalog for each image or use Project -> Resources folder.

And then, use the image name on XAML file. No code needed.

Upon inspecting the Microsoft Docs for this, it is not as easy as just specifying the path.

First, Create an IMarkupExtension

[ContentProperty (nameof(Source))]
public class ImageResourceExtension : IMarkupExtension
{
 public string Source { get; set; }

 public object ProvideValue (IServiceProvider serviceProvider)
 {
   if (Source == null)
   {
     return null;
   }

   // Do your translation lookup here, using whatever method you require
   var imageSource = ImageSource.FromResource(Source, typeof(ImageResourceExtension).GetTypeInfo().Assembly);

   return imageSource;
 }
}

Then consume it in your XAML:

<?xml version="1.0" encoding="UTF-8" ?>
<ContentPage
   xmlns="http://xamarin.com/schemas/2014/forms"
   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
   xmlns:local="clr-namespace:WorkingWithImages;assembly=WorkingWithImages"
   x:Class="WorkingWithImages.EmbeddedImagesXaml">
 <StackLayout VerticalOptions="Center" HorizontalOptions="Center">
   <!-- use a custom Markup Extension -->
   <Image Source="{local:ImageResource WorkingWithImages.beach.jpg}" />
 </StackLayout>
</ContentPage>

Note that you have to add a custom namespace to your page, in this case: xmlns:local="clr-namespace:WorkingWithImages;assembly=WorkingWithImages"

So, I can not display an image using XAML only. I am pretty satisfied with both the answers. Although this is how I displayed the image without pasting into the android and iOS(to their respective folders) and without making IMarkupExtension. I put one line of code into C# code behind and that worked:

myimage.Source = ImageSource.FromResource("MyXamarinProject.logo.jpg");
//logo.jpg must be Embedded Resource.

This could not be the right answer but it can be a choice. Thanks!

I had the same problem on Visual Studio Mac: my XAML :

<Image x:Name="myimage" Source="logo.jpg"/>

my resources was : logo.jpg

But the file was saved in the file system as Logo.jpg (Capital L).

I just modified it to logo.jpg and rebuild all.

Related