2011-07-06 9 views
1

私はドラッグを実装しています。カスタムビューの場合は&です。この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上のドラッグ操作の画像です(アイコンとラベルのある「ドラッグ」) DragDrop

なぜ私のdragImageは灰色のボックスですか?

+0

'-getSnapshotOfView'にメモリリークがあります。返されたイメージを' autorelease'する必要があります。また、 'imageBounds'変数は決して使用しません。しかし、これらの問題はあなたの問題の原因ではありません。 –

+0

カスタムビューの図面コードを投稿できますか? –

+0

私はちょうどコードを修正しました。 私のcustomViewの描画コードはありませんが、IBを使って挿入する装飾要素は2つだけです。 ビューの名前は「ドラッグ可能なビュー」 [Interface Builderのイメージ](http://cl.ly/3C3B1c2B2J3F082b3H0T/Captura_de_pantalla_2011-07-07_a_las_09.37.41.png) – Giuseppe

答えて

4

コメントのIBのスクリーンショットから、あなたのビューがレイヤーバックされているようです。レイヤーバックビューは、通常のウィンドウバッキングストアとは別の独自のグラフィックス領域に描画されます。

このコード:

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

を効果ウィンドウバッキングストアから画素を読み出します。ビューがレイヤーバックされているため、そのコンテンツは取得されません。

レイヤーバックビューなしでこれを試してください。

+0

完璧な答えであるイメージすることができますように! – Giuseppe

関連する問題