在Cocoa的NSView层级中,我找不到任何线条绘制原语。唯一找到的是NSBezierPath
。这是首选的方法吗?还是有其他我未发现的方法?
NSBezierPath
是你应该使用的类。如果你只想从一个点到另一个点画一条直线,可以使用该类方法:
+strokeLineFromPoint:(NSPoint)point1 toPoint:(NSPoint)point2
@interface MyView : NSView {
@private
NSColor *lineColor;
NSInteger clickCount;
}
@end
@implementation MyView
- (void)setLineColor:(NSColor *)color {
if (color != lineColor) {
[lineColor release];
lineColor = [color copy];
[self setNeedsDisplay:YES]; /// We changed what we'd draw, invalidate our drawing.
}
}
- (void)mouseDown:(NSEvent *)mouseDown {
clickCount = (clickCount == 6) ? 0 : (clickCount + 1);
CGFloat hue = clickCount / 6.0;
[self setLineColor:[NSColor colorWithCalibratedHue:hue saturation:1.0 brightness:1.0 alpha:1.0]];
}
- (void)drawRect:(NSRect)dirtyRect {
NSBezierPath *line = [NSBezierPath bezierPath];
[line moveToPoint:NSMakePoint(NSMinX([self bounds]), NSMinY([self bounds]))];
[line lineToPoint:NSMakePoint(NSMaxX([self bounds]), NSMaxY([self bounds]))];
[line setLineWidth:5.0]; /// Make it easy to see
[[self lineColor] set]; /// Make future drawing the color of lineColor.
[line stroke];
}
@end
我尝试了Jon提供的示例,发现需要对上面的代码示例进行2个小修复。
修复后,我发现这段代码非常有用。 注意:您可能还需要dealloc NSColor。
@interface PropertyPropagateView : NSView {
@private
NSColor *lineColor;
NSInteger clickCount;
}
@end
@implementation PropertyPropagateView
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
lineColor=[NSColor blueColor];
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (void)setLineColor:(NSColor *)color {
if (color != lineColor) {
[lineColor release];
lineColor = [color copy];
[self setNeedsDisplay:YES]; /// We changed what we'd draw, invalidate our drawing.
}
}
- (void)mouseDown:(NSEvent *)mouseDown {
clickCount = (clickCount == 6) ? 0 : (clickCount + 1);
CGFloat hue = clickCount / 6.0;
[self setLineColor:[NSColor colorWithCalibratedHue:hue saturation:1.0 brightness:1.0 alpha:1.0]];
}
- (void)drawRect:(NSRect)dirtyRect
{
NSBezierPath *line = [NSBezierPath bezierPath];
[line moveToPoint:NSMakePoint(NSMinX([self bounds]), NSMinY([self bounds]))];
[line lineToPoint:NSMakePoint(NSMaxX([self bounds]), NSMaxY([self bounds]))];
[line setLineWidth:5.0]; /// Make it easy to see
[lineColor set]; /// Make future drawing the color of lineColor.
[line stroke];
}
@end
补充一些信息,我习惯在绘制前后保存和恢复图形状态,以保持操作的流畅性。
- (void)drawRect:(NSRect)dirtyRect {
[[NSGraphicsContext currentContext] saveGraphicsState]
NSBezierPath *line = [NSBezierPath bezierPath];
[line moveToPoint:NSMakePoint(NSMinX([self bounds]), NSMinY([self bounds]))];
[line lineToPoint:NSMakePoint(NSMaxX([self bounds]), NSMaxY([self bounds]))];
[line setLineWidth:5.0]; /// Make it easy to see
[[self lineColor] set]; /// Make future drawing the color of lineColor.
[line stroke];
[[NSGraphicsContext currentContext] restoreGraphicsState]
}