Search code examples
imagexamarinxamarin.formsandroid-image

Unable to set image source programatically in xamarin forms but only when using local images


I'm trying to create a star-rating implementation and though I would have a star container and dynamically add full stars and half stars to achieve this. I am running into an issue creating an image in code and adding it to a container when using local images however. Displaying an image with the source set in xaml works fine, and creating the image from a url and adding it to the container works fine as well. It is only when I am trying to create an image in code using an image in my resource/drawable folder that it fails.

My code is as follows.

Image star = new Image();
star.Source = ImageSource.FromFile("Tamarin_portrait.JPG");
star.HeightRequest = 25;
star.WidthRequest = 25;
star.Aspect = Aspect.AspectFit;
starContainer.Children.Add(star);//No image visible, fails

var star2 = new Image { Source = "Tamarin_portrait.JPG" };
starContainer.Children.Add(star2);
//Ditto above, fails

var webImage = new Image { Source = ImageSource.FromUri(new Uri("https://xamarin.com/content/images/pages/forms/example-app.png")) };
starContainer.Children.Add(webImage);//Image is displayed correctly


<Image Source="Tamarin_portrait.JPG" WidthRequest="50" HeightRequest="50" Margin="10, 10, 10, 10"></Image><!-- In XAML this image display will also work so I know the image itself is valid and available in that drawable folder -->

Does anyone know what I am doing wrong here? The guide for showing local images suggests I am doing it the right way:https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/images?tabs=vswin. Any help would be appreciated.


Solution

  • What about filename? You should have filename which is valid on all platforms. Try change you filename to lowercase.

    That is an information about that in link which you shared.