Fill a Path With A Scaled Image, Ignoring Image Proportions

×

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.

While continuing to rebuild Slider’s background image features, I was forced to rewrite the code that scales an image up/down to Slider’s portal size, ignoring the image’s original proportions. The image also had to be painted within a path, as Slider may have differently shaped corners compared to the image to be scaled.

The below code accomplishes the scaling and painting of the image.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//theImage = the resulting image, that will have a scaled (proportions ignored) version of "bgImage" painted onto it
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]];
 
NSImage bg = [[NSImage alloc] initWithSize: imageSize];
 
//bgImage can be any NSImage
NSSize originalSize = [bgImage size];
[bg lockFocus];
[bgImage drawInRect: NSMakeRect(0, 0, imageSize.width, imageSize.height) 
fromRect: NSMakeRect(0, 0, originalSize.width, originalSize.height) 
operation: NSCompositeSourceOver fraction: 1.0];
 
[bg unlockFocus];
 
NSColor *c = [NSColor colorWithPatternImage:bg];
[c set];
[path appendBezierPathWithRoundedRect:NSMakeRect(0, 0, imageSize.width, imageSize.height) xRadius:10.0 yRadius:10.0];
[aPath fill];
 
[NSGraphicsContext restoreGraphicsState];

“path” could be any NSBezierPath.

Comments (1) | Trackback