【问题标题】:Drag & Drop creation of drag image拖放图像的拖放创建
【发布时间】:2011-07-06 22:35:19
【问题描述】:

我正在为 customView 实现拖放;这个 customView 是 NSView 的子类,包含一些元素。 当我开始对其进行拖动操作时,dragImage 只是一个与 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];
}

这是我用来创建快照的函数:

- (NSImage *) getSnapshotOfView
{
    NSRect rect = [self bounds] ;

    NSImage *image = [[[NSImage alloc] initWithSize: rect.size] autorelease];

    NSRect imageBounds;
    imageBounds.origin = NSZeroPoint;
    imageBounds.size = rect.size;

    [self lockFocus];
    NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:imageBounds];
    [self unlockFocus];

    [image addRepresentation:rep];
    [rep release];

    return image;
}

这是我的 customView 上的拖动操作的图像(带有图标和标签“拖动我”的那个)

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

【问题讨论】:

  • 你在‑getSnapshotOfView有内存泄漏,你需要autorelease返回的图片。此外,您永远不会使用 imageBounds 变量。但是,这些问题并不是问题的根源。
  • 你能发布你自定义视图的绘图代码吗?
  • 我刚刚修复了代码。我的 customView 没有绘图代码,它只有两个我使用 IB 插入的装饰元素。如您所见,视图的名称是“可拖动视图”Interface Builder Image

标签: objective-c cocoa drag-and-drop draggable


【解决方案1】:

从您评论中 IB 的屏幕截图来看,您的视图看起来是有图层支持的。图层支持的视图绘制到它们自己的图形区域,该区域与正常的窗口后备存储区分开。

这段代码:

[self lockFocus];
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:imageBounds];
[self unlockFocus];

有效地从窗口后备存储中读取像素。由于您的视图是图层支持的,因此不会拾取其内容。

在没有图层支持的视图的情况下试试这个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多