Skip to content

Instantly share code, notes, and snippets.

@jeffrafter
Last active August 29, 2015 13:59
Show Gist options
  • Save jeffrafter/10993713 to your computer and use it in GitHub Desktop.
Save jeffrafter/10993713 to your computer and use it in GitHub Desktop.
FunWithNSCursor.m
- (void)cursorUpdate:(NSEvent *)theEvent {
[self.cursor set];
}
- (void)resetCursorRects
{
// ...
}
- (NSImage *)cursorImage
{
if (! _cursorImage) {
int pixelsWide = 100;
int pixelsHigh = 100;
CGContextRef context = NULL;
CGColorSpaceRef colorSpace;
char * bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
bitmapBytesPerRow = (pixelsWide * 4);
bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);
colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
bitmapData = malloc(bitmapByteCount);
if (bitmapData == NULL)
{
fprintf (stderr, "Memory not allocated!");
return NULL;
}
context = CGBitmapContextCreate(bitmapData,// 4
pixelsWide,
pixelsHigh,
8, // bits per component
bitmapBytesPerRow,
colorSpace,
(CGBitmapInfo)kCGImageAlphaPremultipliedFirst);
if (context== NULL)
{
free (bitmapData);
fprintf (stderr, "Context not created!");
return NULL;
}
CGColorSpaceRelease( colorSpace );
CGContextSetRGBFillColor (context, 1, 0, 0, 1);
CGContextFillRect (context, CGRectMake (0, 0, 100, 50 ));
CGContextSetRGBFillColor (context, 0, 0, 1, .5);
CGContextFillRect (context, CGRectMake (0, 0, 100, 100 ));
CGImageRef image = CGBitmapContextCreateImage (context);
CGContextDrawImage(context, CGRectMake(0, 0, 100, 100), image);
_cursorImage = [[NSImage alloc] initWithCGImage:image size:CGSizeMake(100, 100)];
#warning Oh no!
// This needs to go somewhere else I am sure?
CGContextRelease (context);
if (bitmapData) free(bitmapData);
CGImageRelease(image);
}
return _cursorImage;
}
- (NSCursor *)cursor {
if (! _cursor) {
_cursor = [[NSCursor alloc] initWithImage:self.cursorImage hotSpot:NSZeroPoint];
}
return _cursor;
}
@jeffrafter
Copy link
Author

This is some fun code for overwriting the current cursor with an updating image.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment