How to store CGContext state in a NSMutableArray?

678 views Asked by At

I am new to the CGContext world. I need to create a stack of CGContext(s) in a NSMutableArray.

  1. I have a valid PDFContext created with UIGraphicsBeginPDFContextToData

  2. I'm passing this context to a method as an argument

    -(void) drawTo:(CGContextRef) context{}

  3. First I identify the current context with:

    CGContextRef curCon = context;

  4. NSLog value:

    context:<CGContext 0x6b79d60>

  5. Then I attempt to make a copy of the current context:

    CGContextRef conCopy = UIGraphicsGetCurrentContext();

  6. Then I add it to my NSMutableArray:

    [myMutableArray* addObject:(id)conCopy];

  7. Then I list the content of the NSMutableArray:

    after an object added:<__NSArrayM 0x6b7e850>(<CGContext 0x6b79d60>)

And I see that the added value is the same context as originally sent to this method as an argument and not the copy.

What am I missing here ? Or perhaps it's not possible to store the status of current context in a NSMutableArray ? I understand that paths would not get saved, that's fine. I need to save anything and everything about the current context that can be saved. Thank you!

2

There are 2 answers

1
Rob Napier On BEST ANSWER

You can't do this directly. But what's the real problem you're trying to solve? CGContextSaveGState() does what you're asking for, but only within the scope of the current context. CGLayer can effectively create contexts that you can carry around (though you still can't serialize them).

If your real goal is to save non-path state in a copyable form, then you can create a copyable object by calling all the CGContextGet... methods and storing their results. Then you can call CGContextSet... on them to make a new context. It's tedious, but should not be difficult. (Though it does raise the question of why. It feels like a very odd thing to be doing.)

1
Nikolai Ruhe On

UIGraphicsGetCurrentContext does no create a copy. The returned context is there one you created using UIGraphicsBeginPDFContextToData.