在我正在创建的应用程序中,我希望用户按下按钮时某些NSOpenGLViews淡入和淡出视图。为此,我使用NSViewAnimation创建了一个简短的测试应用,试图在十秒钟的时间内淡化视图。该代码紧密基于this post中的代码。

该代码非常适合从NSView继承的常规对象,例如NSBox对象,但是当我尝试将其与NSOpenGLView对象一起使用时,视图在十秒钟内什么也不做,然后突然消失。要使NSViewAnimationNSOpenGLView一起工作,我还需要做些其他事情吗,或者在这种情况下NSViewAnimation不是适合该工作的合适工具吗?

相关代码:

// AppDelegate.m
#import "AppDelegate.h"

@implementation AppDelegate
@synthesize theForeground;  // an instance of a the Foreground class - a subclass of NSOpenGLView
@synthesize theBox;
@synthesize theBackground;

//code omitted

- (IBAction)buttonPressed:(id)sender
{
    NSViewAnimation *theAnim;
    NSMutableDictionary * theViewDict;

    theViewDict = [NSMutableDictionary dictionaryWithCapacity:2];
    [theViewDict setObject: theForeground forKey:NSViewAnimationTargetKey];
    [theViewDict setObject:NSViewAnimationFadeOutEffect
                   forKey:NSViewAnimationEffectKey];

    theAnim = [[NSViewAnimation alloc] initWithViewAnimations:  [NSArrayarrayWithObject:theViewDict]];

    [theAnim setDuration:10.0];
    [theAnim setAnimationCurve:NSAnimationEaseInOut];

    [theAnim startAnimation];

    [theAnim release];
}
@end


// Foreground.m

#import "ForegroundView.h"

@implementation ForegroundView

// code omitted
- (void)drawRect:(NSRect)dirtyRect
{
    glClearColor(0, 0, 0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glColor3f(1.0, 0.0, 0.0);
    glBegin(GL_QUADS);
        glVertex2f(-0.5, -0.5);
        glVertex2f(0.5, -0.5);
        glVertex2f(0.5, 0.5);
        glVertex2f(-0.5, 0.5);
    glEnd();
    glFlush();
}

@end

最佳答案

通过制作一个CAOpenGLLayer子类来绘制OpenGL内容,我设法实现了所需的结果。有关Apple示例代码,请参见here。然后通过以下操作实现淡入和淡出:

- (IBAction)buttonPressed:(id)sender
{
    static int isVisible = 1;
    [theGLView.layer setHidden: isVisible];
    isVisible = (isVisible + 1) % 2;
}

09-27 07:52