jnnguyen
jnnguyen

Reputation: 21

Cropping an image with rounded borders in MAUI

I am trying to get a very simple rounded corner Image in .NET MAUI, in a layout like so:

<Grid Margin="16, 20" RowDefinitions="*, auto">
    <Grid HorizontalOptions="Center" VerticalOptions="Center">
        <Image Source="{Binding ImageSource}" 
               Aspect="AspectFit" 
               Grid.Row="0">
            <Image.Behaviors>
                <behaviors:ClipToBoundsBehavior />
            </Image.Behaviors>
        </Image>
    </Grid>

    <Grid Grid.Row="1" VerticalOptions="End">
        <!-- some buttons you don't need to worry about -->
    </Grid>
</Grid>

It is essentially just a grid with a big area for the image in the middle, and the size and source of the image can be freely changed.

What I have tried:

    protected override void LayoutChildren(double x, double y, double width, double height)
    {
        base.LayoutChildren(x, y, width, height);
        ImageHeight = Image.Height;
    }

The height returns a huge number (~2000) and does not work. I'm not sure why.

public class ClipToBoundsBehavior : Behavior<Image>
{
    private RoundRectangleGeometry _clipGeometry;

    protected override void OnAttachedTo(Image bindable)
    {
        base.OnAttachedTo(bindable);
        _clipGeometry = new RoundRectangleGeometry { CornerRadius = 15 };   

        bindable.Clip = _clipGeometry;

        bindable.SizeChanged += Bindable_SizeChanged;
    }

    protected override void OnDetachingFrom(Image bindable)
    {
        base.OnDetachingFrom(bindable);

        bindable.SizeChanged -= Bindable_SizeChanged;
    }

    private void Bindable_SizeChanged(object sender, EventArgs e)
    {
        if (sender is Image image)
        {
            _clipGeometry.Rect = new Rect(0, 0, image.Width, image.Height);
            image.Clip = _clipGeometry;
        }
    }
}

I am still quite new at this, so any help on deepening my understanding of how this works is completely welcomed. I am also not against trying different routes, since I am getting quite frustrated on how difficult it has been for such a simple thing. Unless I am missing something here.

I appreciate you guys' help!

Upvotes: 1

Views: 407

Answers (1)

Peter Wessberg
Peter Wessberg

Reputation: 1921

If you just want a nice rounded picture to show in your app, you can use Image.Clip. There are also great examples in the samples repo, so go there a take a look if this is not what you wanted.

<Image
    Grid.Column="0"
    Aspect="AspectFill"
    HeightRequest="50"
    Source="{Binding ImageSource}"
    WidthRequest="50">
    <Image.Clip>
        <EllipseGeometry
            Center="25,25"
            RadiusX="25"
            RadiusY="25" />
    </Image.Clip>
</Image>

enter image description here

Upvotes: 2

Related Questions