我已经为图像编辑器做了一个我认为完美的开始。无论您单击何处,它都会绘制一个正方形。我的问题是,当您单击不同的位置或拖动鼠标时,它只是移动正方形(而不是绘制另一个正方形)。如何在自定义 View 中绘制而不将其当前内容“拖动”到任何地方?
这是我的代码:
header (.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
为什么这不起作用?
最佳答案
它会移动当前的矩形,因为这是唯一的矩形。如果您想绘制多个矩形并让它们持续存在,则需要将表示矩形的 NSBezierPath
对象存储在某处(我建议使用 NSArray
),然后迭代数组并绘制每一个。
看看您当前的代码,您应该实现 mouseUp:
并将带有 x 和 y 坐标的 NSBezierPath
对象存储在 NSArray
中。然后在 drawRect:
中,只需循环遍历 NSBezierPath
对象数组并绘制每个对象。
关于objective-c - 如何将自定义 View 放入 NSImageWell 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5643805/