如何将ImageSource设置为Xamarin.Forms.Button?
我正在尝试使用按钮中的图像属性添加背景图像。 我面临的问题是我无法将StreamImageSource设置为按钮背景。 如果我尝试这样做,我会遇到下面给出的错误。
我用来设置Image的代码:
ImageSource iconsource =ImageSource.FromStream(() => new MemoryStream(ImgASBytes)); Button Icon = new Button (); Icon.Image = iconsource ;
我遇到的错误:
错误CS0266:无法将类型’Xamarin.Forms.ImageSource’隐式转换为’Xamarin.Forms.FileImageSource’。 存在显式转换(您是否错过了演员?)
ImageSource.FromStream ()
返回一个StreamImageSource
(参见docs )。 Button.Image
只接受FileImageSource
(参见docs )。
这意味着无论你多么努力地将一个人投入另一个人,你想要实现的目标都行不通。
Button.Image
将接受存储为平台项目中资源的图像,并加载:
Icon.Image = ImageSource.FromFile ("foobar.png");
要么
Icon.Image = "foobar.png";
接受的答案是真的,你不能将 StreamImageSource
为FileImageSource
,我认为真正的问题是如何在PCL中共享图像并在按钮上使用它们,就像创建Image
窗体控件时一样。
答案是让Grid
包含一个Button
和一个Image
对象,其中Image
与Button
重叠。
例如,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);
您可能需要使用尺寸和厚度值,但这应该会为您提供带有图标的可点击按钮。
对于任何可能感到困惑的人,截至2014年1月30日
使用“ Image
视图时,可以将源设置为共享项目或PCL中的图像。 这也在Xamarin的文档中显示: 这里
使用button
,您无法使用存储在共享项目或PCL中的源图像,甚至不会浪费您的时间,因为button
类的Image属性需要在访问PCL中的图像时不兼容的FileImageSource或共享项目。 但是,您可以使用本机项目中加载的图像,这就是为什么您会看到上面的某些人说他们有解决方案
小心文件名中的大写和小写。
我想知道为什么我的按钮图像在模拟器上正确显示,但在我的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")) };
当它编译我然后获得一个未处理的空引用exception与描述:对象引用未设置为对象的实例。 我不确定这是否会帮助其他人试图解决这个问题,但我在同一堵墙上。
- 在SQL Server中存储文件还是将它们保存在文件服务器上?
- System.NullReferenceException未将对象引用设置为对象的实例
- 在使用Fluent Nhibernate Table-Per-Subclass策略时,您能指定标识列吗?
- 使用EA生成类图
- 如何使用WPF用户控件关闭父窗口
- 使用LINQ to SQL的.NET体系结构的最佳设计实践(DAL是否必要?我们能否真正使用POCO?采用设计模式?)
- Graphics.DrawString vs TextRenderer.DrawText?哪个可以提供更好的质量
- 在URL中使用斜杠“/”路由参数
- Asp.Net – 在页面上没有检测到javascript? (更名为标题)