尽管配置正确,Xamarin.Forms 图像仍不显示

问题描述 投票:0回答:1

我在 Xamarin.Forms 应用程序中显示图像时遇到问题。尽管遵循了正确的配置步骤,但图像并未显示。这是我的 XAML 和代码隐藏的简化版本:

XAML:

<ScrollView Orientation="Horizontal">
    <StackLayout x:Name="menuStack1" Orientation="Horizontal">
    </StackLayout>
</ScrollView>

C# 代码隐藏:

public MainPage()
{
    InitializeComponent();
    Add();
}

private void Add()
{
    var image = new Image
    {
        Source = "YourNamespace.icon.png", // Replace YourNamespace with the namespace of your project
        Aspect = Aspect.AspectFit,
        HeightRequest = 50,
        WidthRequest = 50,
        AutomationId = "i"
    };

    // Add this line to check if the image exists
    Console.WriteLine($"Image file exists: {ImageSource.FromResource("YourNamespace.icon.png") != null}");

    image.GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(() => Image_Tapped()) });
    menuStack1.Children.Add(image);
}

private void Image_Tapped()
{
    DisplayAlert("Image Tapped", "Image tapped", "OK");
}

我已验证图像文件已标记为嵌入资源,并且文件路径和命名空间正确。但是,不显示图像。代码中的Console.WriteLine语句提示找不到镜像文件。

什么可能导致此问题?如何排除或解决该问题?我需要采取任何其他步骤来确保图像正确加载吗?

任何指导或建议将不胜感激。谢谢!

c# .net image xamarin xamarin.forms
1个回答
0
投票

您可以参考Xamarin Forms本地图片

对于Android,请使用Build Action: AndroidResource 将图像放置在Android 项目的Resources/drawable 目录中。

对于 iOS,可以使用构建操作:BundleResource 将图像放置在 iOS 项目的资源目录中,或者使用 资产目录图像集

© www.soinside.com 2019 - 2024. All rights reserved.