我正在实施拖拽drop for 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只是一个灰色的盒子?
答案 0 :(得分:4)
在评论的IB屏幕截图中,您的视图看起来像是图层支持的。图层支持的视图绘制到自己的图形区域,该区域与普通窗口后备存储区分开。
此代码:
[self lockFocus];
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:imageBounds];
[self unlockFocus];
从窗口后备存储中有效读取像素。由于您的视图是图层支持的,因此不会拾取其内容。
在没有图层支持视图的情况下尝试此操作。