Search code examples
objective-cuigraphicscontextnscolornsbitmapimagerepgraphicscontext

Change color during the drawing on a NSBitmapImageRep


I implemented a methode that returns a NSBitmapImageRep. Onto that bitmap 10x2 rectangles should be drawn and each rectangle should be filled with the color cyan. But for each rectangle the cyan value should be increased by 12 (value starts at 0).

The result bitmap gets 20 rectangles, like expected. But the color doesn't differ between the rectangles. All rectangles have the same cyan value.

I have no idea what's the problem. Can somebody please give me a hint?

-(NSBitmapImageRep*)drawOntoBitmap
{
   NSRect offscreenRect = NSMakeRect(0.0, 0.0, 1000.0, 400.0);
   NSBitmapImageRep *image = nil;

    image = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil
                                                   pixelsWide:offscreenRect.size.width
                                                   pixelsHigh:offscreenRect.size.height
                                                bitsPerSample:8
                                              samplesPerPixel:4
                                                     hasAlpha:NO
                                                     isPlanar:NO
                                               colorSpaceName:NSDeviceCMYKColorSpace
                                                 bitmapFormat:0
                                                  bytesPerRow:(4 * offscreenRect.size.width)
                                                 bitsPerPixel:32];

   [NSGraphicsContext saveGraphicsState];
   [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:image]];

   NSRect colorRect;
   NSBezierPath *thePath;
   int cyan = 0;
   int x = 0;
   int y = 0;
   int w = 0;
   int h = 0;
   for (intj = 0; j<2; j++)
   {
       y = j * 200;
       h = y + 200;

       for (int i = 0; i<10; i++)
       {
           x = i * 100;
           w = x + 100;

           colorRect = NSMakeRect(x, y, w, h);
           thePath = [NSBezierPath bezierPathWithRect: colorRect];
           cyan += 12;
           [[NSColor colorWithDeviceCyan:cyan magenta:0 yellow:0 black:0 alpha:100] set];
           [thePath fill];
       }
   }

   [NSGraphicsContext restoreGraphicsState];
   return image;
}

For each rect the same color value is used and it's the last cyan value that's set after the both loops are passed.


Solution

  • OK, found out that the NSColor value has a range of 0.0 - 1.0. So I have to set my cyan to float like that:

    cyan += 12/255;
    

    The value has to be smaller than 1.0.