3

I'm trying to draw some of my UI elements in Cocoa, mainly icons for buttons, but I'm having great difficulty getting the kind of precision I'd like.

I'm using super simple code like this to draw rectangles:

[[NSColor redColor] set];
[NSBezierPath strokeRect:myRect];

But what I'm seeing is the red rectangle line is always faded.

What am I missing here?

BenL0
  • 277
  • 1
  • 9
  • NSBezierPath has extreme performance issues, are you sure you want to use it for a rectangle? – Antwan van Houdt Feb 10 '11 at 12:23
  • I assume the original poster intends to do more complex drawing, but first tried to draw a rect. – Jakob Egger Feb 10 '11 at 12:36
  • Yes, this was as simple example as I could make, but I wasn't aware of the performance hit of NSBezierPath so I'll look at alternatives. – BenL0 Feb 11 '11 at 09:22
  • 3
    BenL0: In my experience, NSBezierPath is not THAT bad. If you want to draw several thousand paths, you might run into problems. But avoiding NSBezierPath altogether sounds like premature optimisation. I would search for alternatives only if you detect actual performance problems when testing your app. – Jakob Egger Feb 11 '11 at 09:42

2 Answers2

8

The Cocoa coordinates actually specify the center of the pixel you want to draw. This means, for example, if you want to draw on the bottom left pixel, you should use the coordinates (0.5,0.5).

Add/Subtract half a pixel to your coordinates and they should be pixel-perfect.

Jakob Egger
  • 11,981
  • 4
  • 38
  • 48
0

You can disable antialiasing for your graphics context like this:

[[NSGraphicsContext currentContext] setShouldAntialias:NO];

Or you could use NSFrameRect instead of a bezier path, and that would get the precision you want, while keeping antialiasing on:

NSFrameRect(myRect);
Jesús A. Álvarez
  • 2,958
  • 23
  • 22
  • 1
    well, maybe because disabling antialiasing isn't such a good idea – Jesús A. Álvarez Feb 10 '11 at 19:38
  • It's not the right answer - it's a workaround to the poster's problem. See Jakob's answer. – Jay Mar 27 '12 at 06:40
  • While this fixes the fading, it does ruin one of the defining features of OS X - the incredible antialiasing. If it is just one pixel wide or tall, antialiasing makes it easier to see. If it is a large shape or something, antialiasing is not important (unless you are designing something for graphic design. I am not sure this is worth being voted up or down - it is all a matter of opinion. That said, aliasing ruins the look of text and small shapes. – Justin May 03 '12 at 02:53