Search code examples
objective-ccore-plot

How can I add a layer to core plot graph


Using core plot CPTXYGraph, I want to add a background behind the axes but on top of plot line. As far as my research, the only way to do this is to add a custom CPTLayer, and try to position it correctly. My problem is the CPTLayer always grows to full size of the graph despite the frame I set. How can I solve this? Thanks.

CPTLayer *layer = [CPTLayer layer];
layer.frame = CGRectMake(0, 0, 200, 200);
layer.backgroundColor = [[UIColor colorWithRed:0.1 green:0.2 blue:0.3 alpha:0.6] CGColor];
[self.graph addSublayer:layer];

Solution

  • Make your view a subclass of CPTGraphHostingView

    Then , In Implementation

    CPTXYGraph      *graph;
    
    hostingView = (CPTGraphHostingView *)hostingView;
    hostingView.hostedGraph = graph;
    
    CPTLayer *subLayer = [[CPTLayer alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
    subLayer.backgroundColor = [UIColor redColor].CGColor;
    [self.hostingView.layer addSublayer:subLayer];