单击
按钮后如何在特定窗口中绘制线条?
我正在使用这个:
NSBezierPath * path = [NSBezierPath bezierPath];
[path setLineWidth: 4];
NSPoint startPoint = { 21, 21 };
NSPoint endPoint = { 128,128 };
[path moveToPoint: startPoint];
[path lineToPoint:endPoint];
[[NSColor redColor] set];
[path stroke];
但只有当我把它放在:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
我该如何解决这个问题?我的目标是创建一个可以画线的应用程序,根据收到的详细信息(坐标)
谢谢。
不应在
视图或图层的绘制方法之外进行绘制(例如 drawRect:
)。从广义上讲,您要做的是在那里有一个视图,该视图在设置标志时绘制线条,当您单击按钮时,设置标志并告诉视图重新绘制。
当您单击鼠标事件时。此代码将创建直线、曲线和绘图。
#import <Cocoa/Cocoa.h>
@interface BezierView : NSView {
NSPoint points[4];
NSUInteger pointCount;
}
@end
#import "BezierView.h"
@implementation BezierView
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
}
return self;
}
- (void)drawRect:(NSRect)rect
{
NSBezierPath *control1 = [NSBezierPath bezierPath];
[control1 moveToPoint: points[0]];
[control1 lineToPoint: points[1]];
[[NSColor redColor] setStroke];
[control1 setLineWidth: 2];
[control1 stroke];
NSBezierPath *control2 = [NSBezierPath bezierPath];
[control2 moveToPoint: points[2]];
[control2 lineToPoint: points[3]];
[[NSColor greenColor] setStroke];
[control2 setLineWidth: 2];
[control2 stroke];
NSBezierPath *curve = [NSBezierPath bezierPath];
[curve moveToPoint: points[0]];
[curve curveToPoint: points[3]
controlPoint1: points[1]
controlPoint2: points[2]];
[[NSColor blackColor] setStroke];
CGFloat pattern[] = {4, 2, 1, 2};
[curve setLineDash: pattern
count: 4
phase: 1];
[[NSColor grayColor] setFill];
[curve fill];
[curve stroke];
}
- (void)mouseDown: (NSEvent*)theEvent
{
NSPoint click = [self convertPoint: [theEvent locationInWindow]
fromView: nil];
points[pointCount++ % 4] = click;
if (pointCount % 4 == 0)
{
[self setNeedsDisplay: YES];
}
}
@end