Objective c 拖放创建拖动图像

Objective c 拖放创建拖动图像,objective-c,cocoa,drag-and-drop,draggable,Objective C,Cocoa,Drag And Drop,Draggable,我正在为customView实现拖放;此customView是NSView的一个子类,包含一些元素。 当我开始对它进行拖动操作时,它只是一个与customView大小相同的矩形灰色框 这是我写的代码: -(void) mouseDragged:(NSEvent *)theEvent { NSPoint downWinLocation = [mouseDownEvent locationInWindow]; NSPoint dragWinLocation = [theEvent l

我正在为customView实现拖放;此customView是NSView的一个子类,包含一些元素。 当我开始对它进行拖动操作时,它只是一个与customView大小相同的矩形灰色框

这是我写的代码:

-(void) mouseDragged:(NSEvent *)theEvent
{
    NSPoint downWinLocation = [mouseDownEvent locationInWindow];
    NSPoint dragWinLocation = [theEvent locationInWindow];

    float distance = hypotf(downWinLocation.x - dragWinLocation.x, downWinLocation.y - downWinLocation.x);
    if (distance < 3) {
        return;
    }

    NSImage *viewImage = [self getSnapshotOfView];
    NSSize viewImageSize = [viewImage size];
    //Get Location of mouseDown event
    NSPoint p = [self convertPoint:downWinLocation fromView:nil];

    //Drag from the center of image
    p.x = p.x - viewImageSize.width / 2;
    p.y = p.y - viewImageSize.height / 2;

    //Write on PasteBoard
    NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSDragPboard];
    [pb declareTypes:[NSArray arrayWithObject:NSFilenamesPboardType]
               owner:nil];
    //Assume fileList is list of files been readed
    NSArray *fileList = [NSArray arrayWithObjects:@"/tmp/ciao.txt", @"/tmp/ciao2.txt", nil];
    [pb setPropertyList:fileList forType:NSFilenamesPboardType];

    [self dragImage:viewImage at:p offset:NSMakeSize(0, 0) event:mouseDownEvent pasteboard:pb source:self slideBack:YES];
}
这是我的customView上的拖动操作的图像,带有图标和标签drag me


为什么我的绘图只是一个灰色的框?

从你评论中IB的屏幕截图来看,你的视图似乎是分层的。图层备份视图绘制到其自己的图形区域,该区域与普通窗口备份存储区分开

此代码:

[self lockFocus];
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:imageBounds];
[self unlockFocus];
有效地从窗口备份存储中读取像素。由于您的视图是层备份的,因此不会拾取其内容


在没有分层视图的情况下尝试此操作。

从您评论中IB的屏幕截图来看,您的视图似乎是分层视图。图层备份视图绘制到其自己的图形区域,该区域与普通窗口备份存储区分开

此代码:

[self lockFocus];
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:imageBounds];
[self unlockFocus];
有效地从窗口备份存储中读取像素。由于您的视图是层备份的,因此不会拾取其内容


在没有层备份视图的情况下尝试此操作。

如果‑getSnapshotOfView中存在内存泄漏,则需要自动恢复返回的图像。此外,您从不使用imageBounds变量。但是,这些问题并不是问题的根源。您可以发布自定义视图的绘图代码吗?我刚刚修复了代码。我的customView没有绘图代码,它只有两个装饰元素,我使用IB插入。由于您可以将视图的名称设置为Dragable view,因此‑getSnapshotOfView中存在内存泄漏,您需要自动恢复返回的图像。此外,您从不使用imageBounds变量。但是,这些问题并不是问题的根源。您可以发布自定义视图的绘图代码吗?我刚刚修复了代码。我的customView没有绘图代码,它只有两个装饰元素,我使用IB插入。正如您可以想象的那样,视图的名称是Draggable view