Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want crisp rectangles you need to align coordinates so that they match the underlying pixels. <code>NSView</code> has a method for this purpose: <code>- (NSRect)backingAlignedRect:(NSRect)aRect options:(NSAlignmentOptions)options</code>. Here's a complete example for drawing the grid:</p> <pre><code>const NSInteger GRIDSIZE = 16; - (void)drawRect:(NSRect)dirtyRect { for (NSUInteger x = 0; x &lt; GRIDSIZE; x++) { for (NSUInteger y = 0; y &lt; GRIDSIZE; y++) { NSColor *color = (x % 2 == y % 2) ? [NSColor greenColor] : [NSColor redColor]; [color set]; [NSBezierPath fillRect:[self rectOfCellAtColumn:x row:y]]; } } } - (NSRect)rectOfCellAtColumn:(NSUInteger)column row:(NSUInteger)row { NSRect frame = [self frame]; CGFloat cellWidth = frame.size.width / GRIDSIZE; CGFloat cellHeight = frame.size.height / GRIDSIZE; CGFloat x = column * cellWidth; CGFloat y = row * cellHeight; NSRect rect = NSMakeRect(x, y, cellWidth, cellHeight); NSAlignmentOptions alignOpts = NSAlignMinXNearest | NSAlignMinYNearest | NSAlignMaxXNearest | NSAlignMaxYNearest ; return [self backingAlignedRect:rect options:alignOpts]; } </code></pre> <p>Note that you don't need <code>stroke</code> to draw a game board. To draw pixel aligned strokes you need to remember that coordinates in Cocoa actually point to lower left corners of pixels. To crisp lines you need to offset coordinates by half a pixel from integral coordinates so that coordinates point to centers of pixels. For example to draw a crisp border for a grid cell you can do this:</p> <pre><code>NSRect rect = NSInsetRect([self rectOfCellAtColumn:column row:row], 0.5, 0.5); [NSBezierPath strokeRect:rect]; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload