Search code examples
xamarinopentk

How to add trivial OpenGL functionality to Xamarin forms app


Can anyone please help with the following?

I have a trivial Xamarin forms app working and I want to add an OpenTK view.

The following works fine:

In my MainPage.xaml.cs I have the following event handler for a button which spawns an empty OpenTK view on each click:

private void OnXAMLButtonClicked(object sender, EventArgs e)
        {
            var view = new OpenGLView { HasRenderLoop = true };

            view.HeightRequest = 300;
            view.WidthRequest = 300;

            view.OnDisplay = r =>
            {
                //GL.ClearColor(red, green, blue, 1.0f);
            };

            m_SL.Children.Add(view);
        }

(where m_SL is the name of my StackLayout).

I get a new black window on each click. Great.

Now, see that commented-out line, that's because the value GL is undefined.

This code is from the simple example here:

https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.openglview?view=xamarin-forms

I see at the top of that example there is the following:

using OpenTK.Graphics.ES30;

But I cannot include this, OpenTK is not recognized as a namespace. I expected to have to add it as a reference, but how?

I can add a reference to it in my .Android project so that I can add the above using statement in my MainActivity.cs page but that is not where it belongs (although I see that I then have GL defined, so this proves that I need to add these using statements to my MainPage.xaml.cs in order to get GL defined), but like I say, how do I add the reference to OpenTK for the project that contains MainPage.xaml.cs.

Thanks for any help, Mitch.

----- EDIT -----

Thanks to the poster for helping me so far, the new problem is a reference to System.Private.Core that cannot be resolved. Here's the my full workflow for creating this error:

1: Create a new project.

enter image description here

enter image description here

This gives me the three projects:

enter image description here

2: Change to .NET standard 2.1 in the OGLMobile project:

enter image description here

The .Android and .iOS projects don't have a .NET choice option.

3: Add reference to OpenTK to OGLMobile project:

enter image description here

4: OGLMobile project builds fine but .Android project gives:

enter image description here

If I remove reference to OpenTK everything builds again. Makes no difference if I add OpenTK Nuget package to .Android project, I still get the same error.

So close, thanks for any advice.


Solution

  • You need to install Nuget Package OpenTK.Graphics, then can use that.

    enter image description here

    Now can refer it:

    enter image description here

    Note: 4.0.1 of OpenTK.Graphics need .NET Standard 2.1.

    enter image description here