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:
- Creating a
Frame
or aBorder
surrounding the image, and round the corners that way:- Since the whole thing is wrapped in a
Grid
with row height*
, theFrame
orBorder
ends up stretching the whole screen. - I then tried to fetch the
Image
‘s requested Height upon Content PageLoaded
, and dynamically change the height of theFrame
that way, and even in this function here
- Since the whole thing is wrapped in a
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.
- Creating a clip for the image, using a custom
ClipToBoundsBehavior
, as above. TheImage
will render, but does not clip at all, or clip at very random numbers that is not theImage
‘s height and width. Here is myClipToBoundsBehavior
class:
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!