objective-c - NSGraphicsContext currentContext 返回 nil

标签 objective-c core-plot nsview

这可能是一个基本的新手问题,但我一直被困在这个问题上。尝试设置 Core Plot,但遇到一些问题。

通过查看 CPTestApp,我试图绘制任何内容,但我总是在 CPTPlatformSpecificFunctions 中崩溃,因为 NSGraphicContext 为零。

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?我将不胜感激任何提示。演示应用程序似乎像我一样从应用程序委托(delegate)调用 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 是不是太早了?我错过了什么吗?

最佳答案

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

在 View 级别调用

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

其中 view 是您正在绘制的 View 。

关于objective-c - NSGraphicsContext currentContext 返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26596876/

相关文章:

swift - 通过标识符查找 subview

c++ - 从 UIImage 转换为 cv::Mat,然后返回 UIImage 会降低图像质量

objective-c - 防止 Cocoa 应用程序使用虚拟内存,或者至少在使用后安全地清除它

ios - 核心情节: Align both y-axes to have the same zero-point

objective-c - Core-Plot 中 y 轴标签的四舍五入数字

ios subview 在模拟器中出现颠倒

macos - NSView中的drawRect高效绘图

ios - 为什么我的 UIScrollView 中的 UIView 不滚动?

objective-c - NSView 初始化 : -init: vs. -awakeFromNib: