我正在執行拖動& 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只是一個灰色方塊?
你有'-getSnapshotOfView'內存泄漏,你需要'autorelease'返回的圖像。另外,你從不使用'imageBounds'變量。但是,這些問題不是問題的根源。 –
您可以發佈自定義視圖的繪圖代碼嗎? –
我只是修復了代碼。 我的customView沒有繪圖代碼,它只有兩個裝飾元素,我使用IB插入。 你可以像視圖的名稱爲「可拖動查看」 [Interface Builder的圖片](http://cl.ly/3C3B1c2B2J3F082b3H0T/Captura_de_pantalla_2011-07-07_a_las_09.37.41.png) – Giuseppe