NSBitmapImageRep

How to Prevent Noisy NSBitmapImageReps

Before

Images generated for Slider’s background and tabs contained a lot of noise – random ugly pixels throughout the images.

I was unsure why this was happening, so I asked the Cocoa-Dev mailing list.

Rob Keniger kindly replied with the following solution:

“An NSBitmapImageRep is not guaranteed to be empty when you create it and in general it’s just full of random bits. You need to clear it explicitly if you are drawing non-opaque content”

He included the following snippet that solved my problem nicely:

1
2
3
4
5
6
7
- (void) clearBitmapImageRep:(NSBitmapImageRep *)bitmap {
   unsigned char* bitmapData = [bitmap bitmapData];
   if (bitmapData != NULL)
   {
       bzero(bitmapData, [bitmap bytesPerRow] * [bitmap pixelsHigh]);
   }
}

I call it as soon as I’ve created a new NSBitmapImageRep, like so:

1
2
3
4
5
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];
 
[self clearBitmapImageRep:theImage];

This results in noise-free images.

After

Thanks Rob!

No comments | Trackback