2

Starting from Sierra the's a pdf drawWithBox:toContext: operation available. But in former OS versions this is not present. When there's a graphic context the predecessor drawWithBox: worked nicely where ever a context is present (e.g. in drawRect:). But if you don't have such a context, I don't see a way to use drawWithBox: (except for taking a random context which "might" be present). I tried this:

_contextRef =
  CGBitmapContextCreate(_cvMat.data, ... 

...

if (v12) {
  [page drawWithBox:kPDFDisplayBoxBleedBox toContext:cgContext];
} else {
  [NSGraphicsContext  setCurrentContext:(__bridge NSGraphicsContext * _Nullable)(cgContext)];
  [page drawWithBox:kPDFDisplayBoxBleedBox];
}

but that just dumped

-[__NSCFType graphicsPort]: unrecognized selector sent to instance 0x7f8de1e219a0

which is not an error message encountered (or sought after) very often.

qwerty_so
  • 35,448
  • 8
  • 62
  • 86
  • Possible duplicate of [Mac OS X: Drawing into an offscreen NSGraphicsContext using CGContextRef C functions has no effect. Why?](http://stackoverflow.com/questions/10627557/mac-os-x-drawing-into-an-offscreen-nsgraphicscontext-using-cgcontextref-c-funct) - Definitely this is a duplicate :-) – qwerty_so Jan 30 '17 at 10:43

1 Answers1

1

The problem you have is that CGContextRef and NSGraphicsContext are not the same thing. You're calling +[NSGraphicsContext setCurrent:] with a CGContextRef when its expecting an NSGraphicsContext instance.

The good news is that you can create a NSGraphicsContext from a CGContext quite easily:

CGContextRef cgContext;
NSGraphicsContext *newContext = [[NSGraphicsContext alloc] initWithCGContext:cgContext flipped:NO];
[NSGraphicsContext setCurrent: newContext];

See if that lets you draw your PDF where you expect.

Dave Weston
  • 6,527
  • 1
  • 29
  • 44
  • Where did you get that initializer from? My NSGraphicsContext.h does not have any CGContext-related method and thus the compiler croaks: _No visible @interface for 'NSGraphicsContext' declares the selector 'initWithCGContext:flipped:'_ – qwerty_so Jan 30 '17 at 10:28
  • Anyhow, you lead me in the right direction and I found http://stackoverflow.com/questions/10627557/mac-os-x-drawing-into-an-offscreen-nsgraphicscontext-using-cgcontextref-c-funct which solved my issue. – qwerty_so Jan 30 '17 at 10:42