objective-c - 图片不想拖

标签 objective-c cocoa osx-lion

我正在关注 Aaron 的 Cocoa Mac OS X 编程的第 23 章。
我必须从 View 中拖出一个字母并将其复制到另一个应用程序(如文本编辑)中。
这是我发现问题的代码部分:

- (void) mouseDragged:(NSEvent *)theEvent
{
    NSPasteboard* pb=[NSPasteboard pasteboardWithName: NSDragPboard];
    NSPoint down=[mouseDownEvent locationInWindow];
    NSPoint drag=[theEvent locationInWindow],p;
    NSSize size=[string sizeWithAttributes: attributes];
    NSRect imageBounds;
    NSImage* image=[NSImage alloc];
    float distance;
    distance= hypot(down.x-drag.x, down.y-drag.y);
    if(distance<3 || [string length]==0)
    return;
    image=[image initWithSize: size];
    imageBounds.origin=NSZeroPoint;
    imageBounds.size=size;
    [image lockFocus];
    [self drawStringCenteredIn: imageBounds];
    [image unlockFocus];
    p=[self convertPoint: down fromView: nil];
    p.x= p.x - size.width/2;
    p.y= p.y - size.height/2;
    [self writeToPasteboard: pb];
    [self dragImage: image at: p offset: NSZeroSize event: mouseDownEvent pasteboard: pb source: self slideBack: YES];
}

地点:
- mouseDownEvent 是先前保存的事件,当用户点击讲台时(mouseDown 事件);
- string 是一个 NSMutableAttributesString,一个最多 1 个 lected 的字符串,包含要显示到 View 中的 lecter;

当事件发生时, View 上已经显示了一个字母(因此字符串的长度为 1)。如果我忘记了一些重要信息,请询问。

问题:拖放操作工作正常,但问题是当我拖动图像时,我没有看到图像从它的原始位置移动。
这是我拖动字母时看到的:

enter image description here

这是我应该看到的:

enter image description here

所以字母应该被替换,但这并没有发生。我不知道这个问题的原因,我认为方法 drawImageCenteredIn 应该可以正常工作。这就是这个方法的代码:

- (void) drawStringCenteredIn: (NSRect) rect
{
    NSSize size=[string sizeWithAttributes: attributes];
    NSPoint origin;
    origin.x= rect.origin.x+ (rect.size.width+size.width)/2;
    origin.y=rect.origin.y + (rect.size.height+size.height)/2;
    [string drawAtPoint: origin withAttributes: attributes];
}

最佳答案

很简单。这两行中的符号不​​正确:

  origin.x= rect.origin.x+ (rect.size.width-size.width)/2;
  origin.y= rect.origin.y + (rect.size.height-size.height)/2;

这里是更正的方法:

- (void) drawStringCenteredIn: (NSRect) rect
{
    NSSize size=[string sizeWithAttributes: attributes];
    NSPoint origin;
    origin.x= rect.origin.x+ (rect.size.width-size.width)/2;
    origin.y= rect.origin.y + (rect.size.height-size.height)/2;
    [string drawAtPoint: origin withAttributes: attributes];
}

关于objective-c - 图片不想拖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12486627/

相关文章:

ios - Objective-c:当所有线程完成时返回

ruby-on-rails - 不能使用Rails

macos - 较少编译为空的 CSS 文件

macos - 基于自定义 View 的 NSOutlineView 披露?

ios - 如何让导航栏像iOS中的safari一样随着webview滚动?

objective-c - 如何为导航项目设置动画(闪烁或闪烁之类)

objective-c - 为什么我的 Cocoa 应用程序中的某些行需要永远运行?

objective-c - 绘制透明图像

python - PyObjC + Python 3.0 问题

ios - 在扩展中定义 IBOutlet 属性