BenL0
BenL0

Reputation: 287

How to get pixel perfect drawing with cocoa

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?

Upvotes: 3

Views: 1380

Answers (2)

Jakob Egger
Jakob Egger

Reputation: 12041

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.

Upvotes: 8

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);

Upvotes: 0

Related Questions