【问题标题】:PNG image with transparency not displaying in xamarin forms (xaml)具有透明度的 PNG 图像未以 xamarin 形式显示 (xaml)
【发布时间】:2019-11-30 07:26:48
【问题描述】:

我制作了一个 xamarin 表单登录屏幕,我想在其中放置一个徽标,但它没有显示。我已按照以下链接上的说明进行操作:https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/images?tabs=windows#using-xaml

我正在使用 xaml

我尝试按照上面的链接进行操作,但显示的只是一张空白图片,如果我使用以下链接:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MaisonNickel.MainPage"

             Title="MainPage">

    <ContentPage.Content>
        <Image x:Name="cat" Aspect="AspectFit"/>
    </ContentPage.Content>

</ContentPage>

https://imgur.com/OS5c7cw

也没有显示错误,我检查了过滤器,这是一个不刷新的 vs 错误

【问题讨论】:

  • Xamarin Forms Previewer 有多个错误我建议您开始检查设备...
  • 您似乎没有在图像中添加 Source,您是在后面的代码中进行的吗?如果 Image 组件中没有设置图像源,则不会显示任何内容。
  • 如何添加源?
  • @MateusW。如何添加?
  • 作为答案发布。

标签: xaml xamarin xamarin.forms


【解决方案1】:

您需要将Source 属性添加到您的Image,以便显示一些内容。你这样做(在 XAML 中):

<Image x:Name="cat" Aspect="AspectFit" Source="catImage.png"/>

您的“catImage.png”必须存在于您希望应用运行的平台的资源中。因此,对于 Android,将您的图像添加到 Resources/Drawable,对于 iOS,将其添加到 Resources 文件夹.

您还可以将图像添加到您的主项目一次,并将其用作Embedded Resource。如果你想这样做,我建议阅读this

另外,如果您在项目中使用了大量图像并且它开始失去性能,我建议使用某种缓存图像的方式,为此,我推荐FFImageLoading。它在加载图像时处理缓存、占位符和淡入淡出动画,检查一下!

【讨论】:

    【解决方案2】:

    我不确定您是否遵循了所有说明。这很简单。如果你想通过嵌入式资源添加图像(所以在 Xaml 中)这里是要点:

    1) 将图片导入到您的项目中,并在属性窗口中将其设置为嵌入式资源(假设您的图片名为cat.png,放置在主文件夹中并你的组件是 MaisonNickel)

    2) 在主文件夹中创建一个新的 Xaml 标记扩展

    [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;
     }
    }
    

    3)然后你必须引用程序集并以这种方式替换图像源:

    <?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:MaisonNickel;assembly=MaisonNickel"
       x:Class="MaisonNickel.MainPage">
       <ContentPage.Content>
          <Image x:Name="cat" Source="{local:ImageResource MaisonNickel.cat.png}" Aspect="AspectFit"/>
       </ContentPage.Content>
    </ContentPage>
    

    在您的代码中,我没有看到 imageResource 的任何引用类,Source 属性也没有。

    编码愉快!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 2016-01-23
      • 2010-09-07
      • 2010-12-22
      • 2014-09-30
      • 1970-01-01
      • 2012-01-29
      相关资源
      最近更新 更多