如何将自定义视图放入NSImageWell?

时间:2011-04-13 02:38:13

标签: objective-c cocoa nsview

我已经做了我认为是图像编辑器的完美开端。无论您在哪里点击,它都会画一个正方形我的问题是当你在另一个地方点击或拖动鼠标时,它只是移动方块(而不是绘制另一个方块)。如何在没有“拖动”当前内容的情况下在自定义视图中绘制?

这是我的代码:

标题(.h)

NSBezierPath *thePath;
NSColor *theColor;
NSTimer *updateTimer;
NSPoint *mousePoint;
int testInt = 1;
int x = 0;
int y = 0;

@interface test : NSView {
    IBOutlet NSView *myView;
    IBOutlet NSButton *button;

}

@property (readwrite) NSPoint mousePoint;

@end

.m文件(不管它叫什么)

@implementation test

@synthesize mousePoint;

- (void) mouseDown:(NSEvent*)someEvent {         
    mousePoint = [someEvent locationInWindow];
    NSLog(@"Location: x= %f, y = %f", (float)mousePoint.x, (float)mousePoint.y);
    x = mousePoint.x;
    y = mousePoint.y;
    [button setHidden:TRUE];
    [button setHidden:FALSE];
    [self setNeedsDisplay:YES];

} 

- (void) mouseDragged:(NSEvent *)someEvent {
    mousePoint = [someEvent locationInWindow];
    NSLog(@"Location: x= %f, y = %f", (float)mousePoint.x, (float)mousePoint.y);
    x = mousePoint.x;
    y = mousePoint.y;
    [button setHidden:TRUE];
    [button setHidden:FALSE];
    [self setNeedsDisplay:YES];

}

- (void) drawRect:(NSRect)rect; {
    thePath = [NSBezierPath bezierPathWithRect:NSMakeRect(x, y, 10, 10)];
    theColor = [NSColor blackColor];
    [theColor set];
    [thePath fill];

}

@end

为什么这不起作用?

1 个答案:

答案 0 :(得分:1)

它会移动当前的矩形,因为那是唯一的矩形。如果你想绘制多个矩形并让它们持久化,你需要存储代表矩形的NSBezierPath对象(我建议NSArray),然后遍历数组并绘制每个矩形。

查看当前的代码,您应该实现mouseUp:并将NSBezierPath对象与x和y坐标存储在NSArray中。然后在drawRect:中循环遍历NSBezierPath个对象的数组并绘制每个对象。