【发布时间】: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