gpt4 book ai didi

objective-c - 拖放创建拖动图像

转载 作者:行者123 更新时间:2023-12-03 16:55:25 24 4
gpt4 key购买 nike

我正在为自定义 View 实现拖放;这个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;
}

这是我的自定义 View 上的拖动操作的图像(带有图标和标签“拖动我”的图像) DragDrop

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

最佳答案

从您评论中的 IB 屏幕截图来看,您的 View 似乎是受层支持的。图层支持的 View 绘制到它们自己的图形区域,该区域与普通窗口支持存储分开。

这段代码:

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

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

在没有图层支持的 View 的情况下尝试此操作。

关于objective-c - 拖放创建拖动图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6603865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com