2

I want to draw a 1px wide border around my custom NSView in DrawRect with NSBezierPath:

BorderColor.Set();
var path = NSBezierPath.FromRect(theRect);
path.LineWidth = 1;
path.Stroke();

Now BorderColor is set to NSColor.Gray, which I can see while debugging has an RGBA color code: (127,127,127,255)
But the 1px wide border which appears on the screen gets this color: (194,194,194,255)
When I set the path.LineWidth to 3, than I can see the 3 lines, the middle with wrong color (194..), the 2 wings with color (135,135,135,255) - which is close enough to the wanted (127..) color to be ok.
When I use four piece of 1px wide rectangles for border instead, and Fill these 4 rects, I also get the (135..) color, which is ok again.

I can use this rectangle based solution, I'm only wondering:
Is there a way to achieve the correct color for a 1px wide border with NSBezierPath.Stroke?

nvirth
  • 1,599
  • 1
  • 13
  • 21

1 Answers1

2

Assuming you're setting the stroke color correctly (we don't see how BorderColor is set up) it might be the case that you're measuring the color value on screen, which - in particular for a thin line - might have been anti-aliased so you're not seeing the original color but the output of the anti-aliasing algorithm.

Set the width to something bigger like 10 and measure the color in the middle of the 'blob' to make sure you're not chasing anti-aliasing artefacts..

cacau
  • 3,606
  • 3
  • 21
  • 42
  • Thanks, anti-aliasing caused the problem. Disabling it for the path drawing did the trick: `var context = NSGraphicsContext.CurrentContext;` `context.SaveGraphicsState();` `context.ShouldAntialias = false;` `//...Drawing the path...` `context.RestoreGraphicsState();` – nvirth Sep 16 '15 at 14:11
  • That might not actually be what you want - make sure you align your drawing to pixel boundaries. Turning off anti-aliasing is usually not the actual solution and should be used only under extreme circumstances (can't imagine any, though). – cacau Sep 17 '15 at 05:44
  • Thanks again, you are right, shifting the coordinates of the line with 0.5px (like [here](http://stackoverflow.com/questions/8016618/how-to-get-a-1-pixel-line-with-nsbezierpath?rq=1)) also can solve the problem. I've also seen now, that my 1px wide line was 2px wide in reality before the coordinate shifting (or the anti-alias disabling). I can see this when I draw it into the middle of a view. I've only seen it 1px wide earlier because I've drawn it at the View's Bounds, so the 2. line was clipped. – nvirth Sep 17 '15 at 13:00
  • Great to hear it helped! – cacau Sep 17 '15 at 13:35