Re: Determining CGContext type at runtime

Graham Cox

Thanks — it is a bit kludgey, but might do in a pinch, as you say.

In some cases I can set a flag on my drawing to tell it that the context should be a PDF at that time, since I am responsible for setting up that context in the first place — but at other times (such as printing), I may not get the chance. But I will explore the issue further and see if anything else comes to mind.

cheers, Graham

On 21 Jun 2020, at 5:28 am, Steve Christensen via <punster@...> wrote:

I played around with it and found that bitmap (easy to create) and PDF contexts have the same CFTypeID so no help there, and that there doesn’t appear to be a public context [sub-]type property. One thing I noticed in  run logging was that the context type is available in the description string, so if you’d like a fragile solution then you might do something like this. I’m not advocating for it, but if in a weak moment desperation overwhelms you...

NSString* pdfDescription = [[NSString alloc] initWithFormat:@"%@", pdfContext];
NSString* bitmapDescription = [[NSString alloc] initWithFormat:@"%@", bitmapContext];

NSLog(@"pdf = %@, isPDF = %@", pdfDescription, [pdfDescription containsString:@"PDF"] ? @"YES" : @"NO");
NSLog(@"bitmap = %@, isPDF = %@", bitmapDescription, [bitmapDescription containsString:@"PDF"] ? @"YES" : @"NO");

pdf = <CGContext 0x600001ae0840> (kCGContextTypePDF), isPDF = YES

bitmap = <CGContext 0x600001ae0b40> (kCGContextTypeBitmap)
<<CGColorSpace 0x600000be0c60> (kCGColorSpaceDeviceRGB)>
width = 100, height = 100, bpc = 8, bpp = 32, row bytes = 416 
kCGImageAlphaPremultipliedFirst | 0 (default byte order) | kCGImagePixelFormatPacked (default) , isPDF = NO

On Jun 19, 2020, at 10:23 PM, Graham Cox <graham@...> wrote:

I need to determine whether I am drawing into a CGPDFContext or a different context at runtime.

In AppKit, I can use [NSGraphicsContext currentContextDrawingToScreen], but this is code that is passed a CGContextRef only, so that higher-level API isn’t appropriate. CGPDFContext doesn’t appear to have an associated CGPDFContextGetTypeID() function to compare with the result of CFGetTypeID(), so it’s unclear how I can do this.

The reason I need to so this is that objects I am drawing can have different states according to whether they are selected in the UI or not, but when capturing the drawing into a PDF, the selection state needs to be ignored, so the drawing code needs to be able to detect what context type is so that it can do this.


Join to automatically receive all group messages.