Get the mouse cursor coordinates in .NET Maui on Image click

I'm developing a software in which I need to be able to get the x and y coordinates of the mouse cursor when the user clicks on an image. I know you could do this in visual forms with pictureBoxes, but is it possible in Maui?

I'm actively looking for answers on the Internet. If I find an answer, I'll edit the post for people with the same problem.

Upvotes: 1

Views: 3319

Answers (1)

Liqun Shen-MSFT
Liqun Shen-MSFT

Reputation: 8220

That's what new features of .NET MAUI for .NET 7. For mouse cursor, now we could detect the click(tap) and hover over a control just as ToolmakerSteve suggested in the comment.

A simple example for you:

In the xaml:

<Image
    Source="dotnet_bot.png"
    SemanticProperties.Description="Cute dot net bot waving hi to you!"
    HeightRequest="200"
    HorizontalOptions="Center" >
        <Image.GestureRecognizers>
            <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"/>
        </Image.GestureRecognizers>
</Image>

In the .cs file:

void TapGestureRecognizer_Tapped(System.Object sender, Microsoft.Maui.Controls.TappedEventArgs e)
{
    // Position relative to the container view, that is the image, the origin point is at the top left of the image.
    Point? relativeToContainerPosition = e.GetPosition((View)sender);
    Console.WriteLine(relativeToContainerPosition.Value.X);
    Console.WriteLine(relativeToContainerPosition.Value.Y);
}

Besides, if you want to detect when the pointer enters, exits, and moves within a view, you could also use a PointerGestureRecognizer.

<Image Source="dotnet_bot.png">
    <Image.GestureRecognizers>
        <PointerGestureRecognizer PointerEntered="OnPointerEntered"
                              PointerExited="OnPointerExited"
                              PointerMoved="OnPointerMoved" />
     </Image.GestureRecognizers>
</Image>  

Also, you could get the gesture position when pointer move within the view using Get the gesture position.

void OnPointerExited(object sender, PointerEventArgs e)
{

    // Position relative to the container view
    Point? relativeToContainerPosition = e.GetPosition((View)sender);
}

For more info, you could refer to Recognize a tap gesture and Recognize a pointer gesture.

Hope it works for you.

Upvotes: 1

Related Questions