cocoansviewsubviewnsopenglview

-setWantsLayer causes distortion to NSOpenGLView


This is what I want to do with my NSOpenGLView. Currently the NSOpenGLView covers the entire area of the window and I would like to add buttons, nsviews, and images on top of the NSOpenGLView. I looked through the web and I discovered that [myOpenGLView setWantsLayer:YES]; would allow me to do things like [myOpenGLView addSubView:someView].

This is what I get as a result:

enter image description here

(Somewhat a bad example, since I was watching Family Guy, but proves the fact that the video memory buffer is getting intercepted here)

As you can see it is distorting some video memory buffer onto the window. Now I was doing some debugging and the problem lies with -setWantsLayer. Once I comment out that line in my code, all the OpenGL stuff appears correctly.

This is what I should be getting:

enter image description here

So my question is, how can I correctly display my OpenGL view and at the same time -addSubViews?

Apple has a really good example project of this working called "LayerBackedOpenGLView" (http://developer.apple.com/library/mac/#samplecode/LayerBackedOpenGLView/Introduction/Intro.html) and I've been looking at it for a good time now and I don't know what I'm doing differently in it. One thing that I did notice was that instead of using a NSOpenGLView, Apple uses the NSView and changes the class to a custom class that subclasses NSOpenGLView, while I use the NSOpenGLView and change the class to a custom class that subclasses the NSOpenGLView again. Not sure if that would cause any problems, but I still get the same issue if I change it to a NSView.


Solution

  • I had the same problem myself, but solved it by reading the sample code ReadMe. You need to implement -drawRect: in your NSOpenGLView subclass. Without it, layer-backing is not supported.

    So, implement -drawRect and do your drawing there. One annoying thing with that is that you're probably better off separating the scene from the openglview. That's what they did in the sample code.