You can still make a NSBitmapImageRep manually and then get a NSGraphicsContext from it to draw into.
The following code converts a PDF NSImage ([self image]) into a bitmap alternate image for drawing faster. Saving the graphics state, use setCurrentContext is roughly equivalent to lockFocus. Then draw. Then restoreGraphicsState which serves as unlockFocus
I imagine you can adapt it to suit your needs.
NSSize imgsize = [[self image] size];
NSBitmapImageRep* imageRep = [[NSBitmapImageRep alloc]
initWithBitmapDataPlanes:NULL
pixelsWide:imgsize.width
pixelsHigh:imgsize.height
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSDeviceRGBColorSpace
bytesPerRow:4 * imgsize.width
bitsPerPixel:0
];
NSImage* aimage = [[NSImage alloc] initWithSize:imgsize];
[aimage addRepresentation:imageRep];
[imageRep autorelease];
// Draw into graphics context instead of using lockFocus
NSGraphicsContext *g = [NSGraphicsContext graphicsContextWithBitmapImageRep:imageRep];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:g];
//[aimage lockFocus]; //<- deprecated
NSRect adr = NSMakeRect(0, 0, imgsize.width, imgsize.height);
// ----- draw content here -----
//if ( [[self image] respondsToSelector:@selector(drawInRect:)] ) { //10.9+, so no longer needs alternate...
[[self image] drawInRect:adr];
//} else {
// [[self image] drawInRect:adr fromRect:adr operation: NSCompositingOperationSourceOver fraction:1.0];
//}
//[aimage unlockFocus]; //<- deprecated
[NSGraphicsContext restoreGraphicsState];
[aimage autorelease];
/*
// ---------------- new method without lockFocus/unlockFocus ----------------
NSImage* aimage = [NSImage imageWithSize:imgsize flipped:NO drawingHandler:^BOOL(NSRect dstRect) {
//draw here
[[self image] drawInRect:dstRect];
NSLog(@"_draw code run");
return YES;
}];
// IMPORTANT: this does not do what we want and create a bitmap for faster drawing
// instead it replays vector paths which is NOT what we want, the image is as slow as the original PDF
// if content is bitmaps, then imageWithSize:flipped:drawingHandler: is fine
*/
[self setAltImage:aimage];
Topic:
UI Frameworks
SubTopic:
AppKit
Tags: