Tile an NSImage Within an NSBezierPath

×

This post was originally published in 2009
It may contain stale & outdated information. Or it may have grown more awesome with age, like the author.

Another snippet I had to write during the great Slider rebuild.

I needed to be able to take an NSImage supplied by the user and tile it within an NSBezierPath defined by more user-set values.

The below example uses a rounded rectangle.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
NSBitmapImageRep *theImage = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL pixelsWide:imageSize.width pixelsHigh:imageSize.height
 bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO
 colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:0 bitsPerPixel:0];
 
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:theImage]];
 
//bgImage can be any NSImage
NSColor *c = [NSColor colorWithPatternImage:bgImage];
[c set];
[path appendBezierPathWithRoundedRect:NSMakeRect(0, 0, imageSize.width, imageSize.height) xRadius:10.0 yRadius:10.0];
[path fill];
 
[NSGraphicsContext restoreGraphicsState];
No comments | Trackback