How to add OnTouch Event in android with SkiaSharp

2019-08-24 13:01发布

问题:

I have a problem. I am using SkiaSharp to make a TriangleGrid. Now I am doing drawing the Grid, but now I want to touch a triangle in the grid to color it. To do that I need to add a TouchEvent to the SKCanvasView, but I dont know how to do that.

On the internet I can find the next example:

  • https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/paths/finger-paint
  • https://github.com/mattleibow/SkiaSharpDemo/blob/master/SkiaSharpDemo/SkiaSharpDemo/MainPage.xaml

But I am using Xamarin Android and those example doesn't work in my code. I also tried to use:

skiaView = FindViewById<SkiaSharp.Views.Android.SKCanvasView>(Resource.Id.skiaView);
skiaView.SetOnTouchListener += OnTouch;

But that gives me the error: "Cannot assign to 'SetOnTouchListener' because it's a 'method group'"

Can anyone help me to get a TouchListener on my SkiaSharp canvas!?

回答1:

You are using the wrong method to add event ,you could set OnTouch event like this:

skiaView= FindViewById<SKCanvasView>(Resource.Id.skiaView);
skiaView.Touch += onTouch;

private void onTouch(object sender, View.TouchEventArgs e)
  {
     Toast.MakeText(this, "touch", ToastLength.Short).Show();
  }

or :

public class MainActivity : AppCompatActivity,View.IOnTouchListener
  {
    private SKCanvasView skiaView;
    protected override void OnCreate(Bundle savedInstanceState)
      {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.Main);
        skiaView= FindViewById<SKCanvasView>(Resource.Id.skiaView);
        skiaView.SetOnTouchListener(this);  
        ...
      }
    public bool OnTouch(View v, MotionEvent e)
      {
        Toast.MakeText(this,"touch",ToastLength.Short).Show();
        return true;
      }
  }