如何在NSTextView中制作可选图像?

时间:2012-11-20 12:00:30

标签: nstextview nsimage nsbezierpath nsimagecell nstextattachment

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

此代码在输出时工作正常,但这就是问题所在:我希望用户可以选择/复制并将生成的图像拖放到其他文本编辑器(如页面或文本编辑)中。 当用户从我的textview拖动图像时,它会被拖动,但没有任何内容粘贴到目标:

  
      
  • (void)drawRect:(NSRect)dirtyRect {

         

    [super drawRect:dirtyRect];

         

    NSBezierPath * aPath = [NSBezierPath bezierPath];

         

    NSImage * anImage = [[NSImage alloc] initWithSize:NSMakeSize(200.0,200.0)];

         

    [anImage lockFocus];

         

    //一些图纸:

    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];

         

    //只附加一次attrited字符串。标题中的BOOL isDrownYet

         

    if(!isDrownYet){

    NSTextAttachmentCell *attachmentCell1 = [[NSTextAttachmentCell alloc]   initImageCell:newImage];
    
    NSTextAttachment *attachment1 = [[NSTextAttachment alloc] init];
    
    [attachment1 setAttachmentCell: attachmentCell1 ];
    
    NSMutableAttributedString *attributedString1 = ( NSMutableAttributedString*)[ NSMutableAttributedString 
    
         

    attributionStringWithAttachment:attachment1];

    [self.textStorage appendAttributedString:attributedString1];
    
    isDrownYet=YES;
    
         

    }   }

  •   

0 个答案:

没有答案