无法以 xamarin 形式以编程方式设置图像源,但仅在使用本地图像时

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

我正在尝试创建一个星级评定实现,虽然我会有一个星级容器并动态添加满星和半星来实现这一点。但是,我 运行 在使用本地图像时遇到了在代码中创建图像并将其添加到容器中的问题。使用 xaml 中设置的源显示图像效果很好,从 url 创建图像并将其添加到容器中也可以正常工作。只有当我尝试使用我的 resource/drawable 文件夹中的图像在代码中创建图像时才会失败。

我的代码如下

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 -->

有谁知道我在这里做错了什么?显示本地图像的指南建议我以正确的方式进行操作:https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/images?tabs=vswin。任何帮助将不胜感激。

文件名呢?您应该具有在所有平台上都有效的文件名。尝试将文件名更改为小写。

这是您在 link 中分享的信息。