Reputation: 21
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:
Frame
or a Border
surrounding the image, and round the corners that way:
Grid
with row height *
, the Frame
or Border
ends up stretching the whole screen.Image
's requested Height upon Content Page Loaded
, and dynamically change the height of the Frame
that way, and even in this function here 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.
Clip
for the image, using a custom ClipToBoundsBehavior
that will change the shape as the image's shape changes. The Image
will render, but does not clip at all, or clip at very random numbers that is not the Image
's height and width. Here is my ClipToBoundsBehavior
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!
Upvotes: 1
Views: 407
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>
Upvotes: 2