NSBezierPath rounded rectangle has bad corners
Asked Answered
M

2

9

I have an NSBezierPath that makes a rounded rectangle but the corners of it look choppy and appear brighter that the rest of the stroke when viewed at full scale. My code is:

 NSBezierPath *path = [NSBezierPath bezierPath];
    [path appendBezierPathWithRoundedRect:NSMakeRect(0, 0, [self bounds].size.width, [self bounds].size.height) xRadius:5 yRadius:5];

    NSGradient *fill = [[NSGradient alloc] initWithColorsAndLocations:[NSColor colorWithCalibratedRed:0.247 green:0.251 blue:0.267 alpha:0.6],0.0,[NSColor colorWithCalibratedRed:0.227 green:0.227 blue:0.239 alpha:0.6],0.5,[NSColor colorWithCalibratedRed:0.180 green:0.188 blue:0.196 alpha:0.6],0.5,[NSColor colorWithCalibratedRed:0.137 green:0.137 blue:0.157 alpha:0.6],1.0, nil];
    [fill drawInBezierPath:path angle:-90.0];

    [[NSColor lightGrayColor] set];
    [path stroke];

Heres a picture of 2 of the corners (Its not as obvious in a small picture):

corners

Anyone know what's causing this? Am I just missing something?

Thanks for any help

Manutius answered 19/4, 2011 at 20:11 Comment(0)
M
19

The straight lines of the roundrect are exactly on the borders of the view, so half the width of each line is getting cut off. (As if they were on a subpixel.)

Try changing

NSMakeRect(0, 0, [self bounds].size.width, [self bounds].size.height)

to

NSMakeRect(0.5, 0.5, [self bounds].size.width - 1, [self bounds].size.height - 1)

If an NSBezierPath ever looks a bit weird or blurry, try shifting it over half a pixel.

Milone answered 19/4, 2011 at 21:8 Comment(2)
Rather than shifting it by half a pixel, it is usually a better idea to inset the drawing by half of the stroke width of the path, which is what you're code actually does here.Nullity
Shorter way: NSInsetRect(self.bounds, 0.5, 0.5)Longlegged
G
0

Take a look at the setFlatness: method in the NSBezierPath docs. It controls how smooth rendered curves are. I believe setting it to a smaller number (the default being .6) will yield smoother curves, at the cost of more computation (though for simple paths, I doubt it matters a whole lot).

Generalship answered 19/4, 2011 at 20:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.