objective-c - 如何将自定义 View 放入 NSImageWell 中?

标签 objective-c cocoa nsview

我已经为图像编辑器做了一个我认为完美的开始。无论您单击何处,它都会绘制一个正方形。我的问题是,当您单击不同的位置或拖动鼠标时,它只是移动正方形(而不是绘制另一个正方形)。如何在自定义 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/

相关文章:

cocoa - 将 subview 添加到 NSView 以获得类似国际象棋的网格

iphone - 多个 Controller 使用一个 xib

ios - 更改 iOS 11 大标题颜色

objective-c - AbsoluteToNanoseconds 与 AbsoluteToDuration

objective-c - 如何才能专门捕获修饰键?

objective-c - 我可以在 NSView 的工具提示内添加超链接吗?

objective-c - iPhone 的高分辨率计时器?

ios - 静态菜单场景中的 SpriteKit 内存泄漏

ios - 如何裁剪较大的图像以适应以编程方式构建的 tabBarController 中的 tabBar 图标。

cocoa - Swift 3 加载 xib。 NSBundle.mainBundle().loadNibNamed 返回 Bool