NSGraphicsContext currentContext返回nil

时间:2014-10-27 21:09:06

标签: objective-c core-plot nsview

这可能是一个基本的新手问题,但我一直坚持这个。试图设置Core Plot但有一些问题。

通过查看CPTestApp,我只想绘制任何东西,但我总是在CPTPlatformSpecificFunctions中崩溃,因为NSGraphicContext是nil。

void CPTPushCGContext(CGContextRef newContext)
{
    if ( newContext ) {
        if ( !pushedContexts ) {
            pushedContexts = [[NSMutableArray alloc] init];
        }
        [pushedContexts addObject:[NSGraphicsContext currentContext]];
        [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:newContext flipped:NO]];
    }
}

为什么[NSGraphicsContext currentContext]返回nil?我会很感激任何提示。演示应用程序似乎像我一样从应用程序委托调用init。

编辑,这是我对Coreplot的调用:

ApplicationDeletegate.h

#import <CorePlot/CorePlot.h>

@property (nonatomic, readwrite, strong) IBOutlet CPTGraphHostingView *graphHostView;

ApplicationDeletegate.m(是的,我知道你这里不应该有这么多代码)

-(void)awakeFromNib
{
    [super awakeFromNib];
    [self setupGraph];
}

-(void)setupGraph
{

    CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:graphHostView.bounds];
    graph.plotAreaFrame.masksToBorder = NO;
    graphHostView.hostedGraph = graph;

    [graph applyTheme:[CPTTheme themeNamed:kCPTPlainBlackTheme]];
    graph.paddingBottom = 30.0f;
    graph.paddingLeft  = 30.0f;
    graph.paddingTop    = -1.0f;
    graph.paddingRight  = -5.0f;

    CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle];
    titleStyle.color = [CPTColor whiteColor];
    titleStyle.fontName = @"Helvetica-Bold";
    titleStyle.fontSize = 16.0f;

    NSString *title = @"Portfolio Prices: April 23 - 27, 2012";
    graph.title = title;
    graph.titleTextStyle = titleStyle;
    graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
    graph.titleDisplacement = CGPointMake(0.0f, -16.0f);

}

awakeFromNib太早了吗?我错过了什么吗?

2 个答案:

答案 0 :(得分:2)

你可能在drawRect:call链之外进行调用。发生这种情况时,即使您获得currentContext,也不会设置graphicsPort或CGContexts(OS X 10.0及更高版本)。

在视图级别,调用

[<view> lockFocus];
<your call to munge the context>
[<view> unlockFocus];

其中view是您正在绘制的视图。

答案 1 :(得分:0)

也许现在没有currentContext?您正在设置一个,所以只需修改您的代码,如果没有,则不要推送。之后验证设置它会导致currentContext返回您设置它的对象。

}
NSGraphicsContext *ctx = [NSGraphicsContext currentContext];
if(ctx != nil) {
    [pushedContexts addObject: ctx];
}
[NSGraph.....

如果你的pushContexts用完了,还要检查你的pop以确保它不会做任何麻烦。

相关问题