How to set ImageSource as Xamarin.Forms.Button?
ImageSource.FromStream ()
returns a StreamImageSource
(see docs). Button.Image
accepts only FileImageSource
(see docs).
It means that what you're trying to achieve won't work, no matter how hard you try to cast one into the other.
Button.Image
will accept images stored as resources in your platform projects, and loaded either with:
Icon.Image = ImageSource.FromFile ("foobar.png");
or
Icon.Image = "foobar.png";
The accepted answer is true that you can't cast StreamImageSource
to FileImageSource
, I think that the real question is about how to share images in a PCL and use them on a button, just like one would when creating an Image
forms control.
The answer is to have a Grid
which contains both a Button
and an Image
object, where the Image
overlaps the Button
.
For example, the C# code might look like this:
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);
You may have to play with the sizes and thickness values but this should get you a clickable button with an icon.