Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do lockFocus and unlockFocus actually do?

Tags:

cocoa

drawing

Warning: I'm a Cocoa newbie.

I'm reading "Cocoa Programming For Mac OS X" by Hillegass.

On p.301 it's written:

To make the drawing appear on the image instead of on the screen, you must first lock focus on the image. When the drawing is complete, you must unlock focus.

The code I have, inside -(void)mouseDragged:(NSEvent *)theEvent of an NSView is as follows:

[resizedImage lockFocus];
[sourceImage drawInRect: NSMakeRect(0, 0, resizeWidth, resizeHeight) fromRect: NSMakeRect(0, 0, originalSize.width, originalSize.height) operation: NSCompositeSourceOver fraction: 1.0];
[resizedImage unlockFocus];

Without the lock/unlock, this does not work, but I still don't understand exactly what is going on.

I see that the 2nd line of code has no mention of resizedImage so does that mean when I use lockFocus it makes sure any 'drawing' that happens takes place there? Could someone explain this better?

like image 550
Vamos Avatar asked Feb 18 '11 17:02

Vamos


1 Answers

Drawing requires a 'graphics context'. You'll notice that, unlike Core Graphics, none of the AppKit drawing methods take a parameter that specifies where the drawing ends up. Instead, the destination is stored globally as [NSGraphicsContext currentContext]. All AppKit drawing methods affect this current context.

The main purpose of -lockFocus (on images and views alike) is to set up the graphics context so your drawing ends up going where you want it to.

like image 180
kperryua Avatar answered Nov 15 '22 18:11

kperryua