xamlmaui

How to resize image inside <Button> in .NET MAUI


I'm new to .NET Maui and XAML and I'm trying to make a simple button menu.

When I uso the image fills in all the space and text label doesnt show. Buttons are intented to show icons, but when using the icons they also get streched.

https://learn.microsoft.com/en-us/dotnet/maui/user-interface/controls/button?view=net-maui-7.0

Note

While Button defines an ImageSource property, that allows you to display a image on the Button, this property is intended to be used when displaying a small icon next to the Button text.


This is the code and result:

    <Button HeightRequest="300"
            WidthRequest="300"
            BorderColor="Blue"
            BorderWidth="3"
            BackgroundColor="Grey"
            Text="TEXT INSIDE BUTTON"
            FontSize="12"
            FontAttributes="Bold"
            ImageSource="https://aka.ms/campus.jpg"
            ContentLayout="Top, 1">

    </Button>

result


What I would like to achieve is something similar to card with border, image and text

desired result

NET MAUI documentation, Youtube tutorial and so on. Pretty new to XAML


Solution

  • It seems there is no a such Button control can achieve the effect you want. So you can use a control to contain the image and the text. And then use the TapGestureRecognizer to deal with the clicked event. Such as:

        <Frame HeightRequest="150" WidthRequest="150" BorderColor="Red"
               Margin="20" >
            <VerticalStackLayout Margin="-10">
                <Image Source="image.png" 
                       WidthRequest="100" 
                       HeightRequest="100" 
                       Margin="-10"/>
                <Label Margin="0" Text="this is text" 
                       WidthRequest="100"
                       HeightRequest="50" 
                       HorizontalTextAlignment="Center"
                       VerticalTextAlignment="Center"/>
            </VerticalStackLayout>
            <Frame.GestureRecognizers>
                <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"/>
            </Frame.GestureRecognizers>
        </Frame>
    

    The Margin property can be used to adjust the fine position of the view.

    And in the Page.cs:

        private void TapGestureRecognizer_Tapped(object sender, TappedEventArgs e)
        {
            // you can do the work you want when the button clicked
        }
    

    The result picture:

    enter image description here

    In addition, you can refer to this case about how to change xamarin frame border thickness to set the frame's border width.