How to set ImageSource as Xamarin.Forms.Button?

后端 未结 6 1428
野性不改
野性不改 2021-01-04 11:28

I am trying add a background image using the image property in button. The issue I\'m facing is that i can\'t set StreamImageSource as button background. I encountered the e

6条回答
  •  一个人的身影
    2021-01-04 12:01

    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.

提交回复
热议问题