如何将 ImageSource 设置为 Xamarin.Forms.Button

本文关键字:Xamarin Forms Button 设置 ImageSource | 更新日期: 2023-09-27 18:24:55

我正在尝试使用按钮中的图像属性添加背景图像。我面临的问题是我无法将流图像源设置为按钮背景。如果我尝试这样做,我遇到了下面给出的错误。

我用来设置图像的代码:

            ImageSource iconsource =ImageSource.FromStream(() => new MemoryStream(ImgASBytes));
            Button Icon = new Button ();
            Icon.Image = iconsource ;

我遇到的错误:

错误 CS0266:无法将类型"Xamarin.Forms.ImageSource"隐式转换为"Xamarin.Forms.FileImageSource"。存在显式转换(您是否缺少强制转换?

如何将 ImageSource 设置为 Xamarin.Forms.Button

ImageSource.FromStream ()返回一个StreamImageSource(请参阅文档(。 Button.Image只接受FileImageSource(请参阅文档(。

这意味着你试图实现的目标不会奏效,无论你多么努力地将一个投入到另一个中。

Button.Image将接受作为资源存储在平台项目中的图像,并加载:

Icon.Image = ImageSource.FromFile ("foobar.png");

Icon.Image = "foobar.png";

公认的答案是真的,你不能StreamImageSourceFileImageSource,我认为真正的问题是关于如何在 PCL 中共享图像并在按钮上使用它们,就像创建Image表单控件时一样。

答案是有一个同时包含ButtonImage对象的Grid,其中ImageButton重叠。

例如,C# 代码可能如下所示:

ImageSource imageSource = ImageSource.FromStream(() => new MemoryStream(imageAsBytes));
Button iconButton = new Button ();
iconButton.VerticalOptions = LayoutOptions.FillAndExpand;
iconButton.HorizontalOptions = LayoutOptions.FillAndExpand;
var image = new Image();
image.Source = imageSource;
// So it doesn't eat up clicks that should go to the button:
image.InputTransparent = true;
// Give it a margin so it doesn't extend to the edge of the grid
image.Margin = new Thickness(10);
var grid = new Grid();
// If we don't set a width request, it may stretch horizontally in a stack
grid.WidthRequest = 48;
// Add the button first, so it is under the image...
grid.Children.Add(iconButton);
// ...then add the image
grid.Children.Add(image);

您可能需要使用尺寸和厚度值,但这应该会为您提供一个带有图标的可点击按钮。

从 Xamarin.Forms 3.4.0 开始,您现在可以使用 ImageButton。 您可以使用本 MS 文档中介绍的扩展方法来使用嵌入的图像

注意文件名中的大写和小写。

我想知道,为什么我的按钮图像在模拟器上正确显示,而不是在我的iPhone上。

在设备上,文件名必须完全匹配,模拟器不关心文件名中的大写和小写。

我用这个,它可以工作

var imageA = new Image();
imageA.Source=(FileImageSource)ImageSource.FromFile(allergeneLocation)};

var imageA = new Image()
{
BackgroundColor = Color.Teal,
Source = (FileImageSource)ImageSource.FromFile(allergeneLocation)},
};

这是我尝试过的:

Button refreshBut = new Button
        {
            Image = (FileImageSource)
            (ImageSource.FromFile("refreshBut.png"))
        };

在编译时,我得到了一个未经处理的空引用异常,其描述如下:对象引用未设置为对象的实例。我不确定这是否会帮助其他人尝试解决这个问题,但我在同一堵墙上。