.netxamlmauigestureabsolutelayout

.net v8 MAUI: How to display an image at last tap location?


Using .net8 MAUI for iOS, I display an image in an iOS App. It has some "hot zones", which are invisible buttons. They will trigger some kind of action (e.g. raising the score).

I want to display a special kind of "mouse cursor" (I will use a .png for it) exactly where the user tapped. I can display the cursor (png-image) anywhere I want using an AbsoluteLayout, using AbsoluteLayout.LayoutBounds. However, I do not manage to dynamically update this location in C#. Any thoughts on this?

Cursor myCursor = new Cursor("custom.cur"); --> no success, requires Cursor Class.


Solution

  • I think you could simply use GestureRecognizers. I've tried it on android, but it should work on ios the same way:

    xaml:

    <?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="ImageTap.MainPage"
                 Shell.NavBarIsVisible="False">
        <AbsoluteLayout>
            <VerticalStackLayout
                BackgroundColor="Blue" AbsoluteLayout.LayoutBounds="0,0,1000,1000">
                <VerticalStackLayout.GestureRecognizers>
                    <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" NumberOfTapsRequired="1" />
                </VerticalStackLayout.GestureRecognizers>
            </VerticalStackLayout>
            <Image x:Name="cursor" Source="cursor.png" AbsoluteLayout.LayoutBounds="0,0,128,128"></Image>
        </AbsoluteLayout>
    </ContentPage>
    

    cs:

    namespace ImageTap
    {
        public partial class MainPage : ContentPage
        {
    
            public MainPage()
            {
                InitializeComponent();
            }
    
            private void TapGestureRecognizer_Tapped(object sender, TappedEventArgs e)
            {
                Point? clickedPosition = e.GetPosition((View)sender);
                cursor.TranslationX = clickedPosition.Value.X;
                cursor.TranslationY = clickedPosition.Value.Y;
            }
        }
    }