I have a general question concerning drawing pretty simple shapes in an NSView
. Is there a "rule" when to use the NSRect
class struct (drawrect
) versus using the CoreGraphics
framework?
What I understood so far I could use either one for my osx application. Can I?
First off, there is no NSRect
class (it's a struct), you're referring to the NSView
method drawRect:
. Generally speaking, the Core Graphics framework is "lower-level" than the AppKit drawing methods, which are usually just "wrappers" around Core Graphics. It's also plain C instead of Objective-C, so AppKit is typically a bit easier to use, but you can mix and match freely between the two.
For example:
- (void)drawRect:(NSRect)rect
{
//This uses AppKit:
[[NSColor redColor] set];
[[NSBezierPath bezierPathWithOvalInRect:[self bounds]] fill];
//This does the same, using Core Graphics:
CGContextRef ctx = [[NSGraphicsContext currentContext] graphicsPort];
CGContextSetRGBFillColor(ctx, 1.0, 0.0, 0.0, 1.0);
CGContextFillEllipseInRect(ctx, NSRectToCGRect([self bounds]));
}