SuperBerry SuperBerry - 2 months ago 11x
Objective-C Question

How to change mouse cursor in Xcode on OS X?

I have made a painting program on OS X. When I change to the Brush function, I want the mouse cursor to be changed to a rectangle cursor. The rectangle size would be the brush size. If the brush size is 10px, the mouse cursor would be 10X10px rectangle.

How can I do that by Objective-C? How to draw the cursor and set it? Thanks a lot.


You'll need to work with NSCursor to create a custom cursor. The cursor needs an NSImage as it's look and an NSPoint as the cursors hot spot.

The NSImage could be loaded from an image or create manually. You can add this in the viewDidLoad method of your ViewController. Store the cursor as attribute of that class. It's of course also possible to do this in the NSView-Subclass itself (in awakeFromNib for example):

NSSize cursorSize = NSMakeSize(10, 10);

NSImage *cursorImg = [[NSImage alloc] initWithSize: cursorSize];
// Draw any color on the image
[cursorImg lockFocus];
[[NSColor blackColor] setFill];
[NSBezierPath fillRect:NSMakeRect(0, 0, cursorSize.width, cursorSize.height)];
[cursorImg unlockFocus];
cursor = [[NSCursor alloc] initWithImage:cursorImg hotSpot:NSMakePoint(cursorSize.width/2.0, cursorSize.height/2.0)];

// you now have a cursor. You must set it (e.g. in mouseEntered-method of a view:

[cursor setOnMouseEntered:YES];
[self.view addTrackingRect:self.view.bounds owner:cursor userData:NULL assumeInside:YES];

You could change the color and the size of the cursor by adapting the NSColor and the NSSize cursorSize. Remember to call removeTrackingRect on the NSView when you're done with the cursor (at latest, when the NSViewController is deallocating).

See apple doc for NSCursor for how to work with cursors in Cocoa.