Search code examples
xamarinskiasharpxamarin-forms-4

SkiaSharp make a bitmap on a path clickable


i have drawn a circle path and for every 1 degree angle am adding a bitmap. Now, i want to listen to each bitmap clicks on that Circle path using Xamarin forms!How can i achieve this. I have followed manipulating touches on xamarin and amble to get touch coordinates but unable to get exactly which bitmap is selected?

EDIT:

 foreach (var item in bitmapPoints)
  {
    using (Stream streami = assembly.GetManifestResourceStream(resID))
    {
      redBitmap = SKBitmap.Decode(streami);
    }
      canvas.DrawBitmap(redBitmap,item, null);
  }

Now am trying to enable click event for each bitmap drawn on Canvas. Should i make custom BitMap class having HiTest method? if so, what should be the Rect x and y to be passed to get HiTest?


Solution

  • this is called "Hit Testing" - Xamarin has a sample in their SkiaSharp docs

    public bool HitTest(SKPoint location)
    {
        // Invert the matrix
        SKMatrix inverseMatrix;
    
        if (Matrix.TryInvert(out inverseMatrix))
        {
            // Transform the point using the inverted matrix
            SKPoint transformedPoint = inverseMatrix.MapPoint(location);
    
            // Check if it's in the untransformed bitmap rectangle
            SKRect rect = new SKRect(0, 0, bitmap.Width, bitmap.Height);
            return rect.Contains(transformedPoint);
        }
        return false;
    }