2

我正在开发一个应用程序,它执行一些数学计算并将结果(包括文本和图形)发送到 NSTextView。

这段代码在制作输出时效果很好,但这就是问题所在:我希望用户可以选择/复制并将生成的图像拖放到其他文本编辑器(如页面或文本编辑)中。当用户从我的文本视图中拖动图像时,它被拖动但没有粘贴到目的地:

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];

    NSBezierPath* aPath=[NSBezierPath bezierPath];

    NSImage* anImage = [[NSImage alloc] initWithSize:NSMakeSize(200.0, 200.0)];
    [anImage lockFocus];
    //some drawings:
    NSColor* blue= [NSColor blueColor];
    [blue setStroke];
    aPath=[NSBezierPath bezierPath];
    [aPath setLineWidth:20];
    [aPath moveToPoint:NSMakePoint(20.0, 20.0)];
    [aPath lineToPoint:NSMakePoint(100.0, 100.0)];
    [aPath stroke];
    [anImage unlockFocus];
    //re-capture and change it to a bitmap

    NSSize size = [anImage size];
    [anImage lockFocus];
    NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0,0,size.width,size.height)];
    [anImage unlockFocus];
    NSData* jpgData = [rep representationUsingType:   NSJPEGFileType properties:nil ];

    NSImage* newImage= [[NSImage alloc]initWithData:jpgData];

    //append attrited string only once.   BOOL isDrownYet in header
    if (!isDrownYet) {
        NSTextAttachmentCell *attachmentCell1 = [[NSTextAttachmentCell alloc]   initImageCell:newImage];
        NSTextAttachment *attachment1 = [[NSTextAttachment alloc] init];
        [attachment1 setAttachmentCell: attachmentCell1];
        NSMutableAttributedString *attributedString1 = (NSMutableAttributedString*)[ NSMutableAttributedString attributedStringWithAttachment: attachment1];
        [self.textStorage appendAttributedString:attributedString1];
        isDrownYet=YES;
    }
 }
4

0 回答 0