4

我有一个带有图像的 NSTextView。我想为这些图像添加跟踪区域。我需要保存图像的单元格框架以创建跟踪区域。

所以我的问题是:如何在 NSTextView 的坐标系中获取 NSTextAttachments 的框架?

我正在以编程方式更改文本视图中图像的大小,此时我需要创建这个新的跟踪区域。我正在执行以下操作来创建带有文本附件的属性字符串,然后以编程方式将其插入到我的文本视图的属性字符串中。但是一旦我完成了所有这些,我就不知道如何为新附件创建我的跟踪区域。

-(NSAttributedString*)attributedStringAttachmentForImageObject:(id)object {
    NSFileWrapper* fileWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:[object TIFFRepresentationUsingCompression:NSTIFFCompressionLZW factor:1.0]];
    [fileWrapper setPreferredFilename:@"image.tiff"];
    NSTextAttachment* attachment = [[NSTextAttachment alloc] initWithFileWrapper:fileWrapper];
    NSAttributedString* aString = [NSAttributedString attributedStringWithAttachment:attachment];
    [fileWrapper release];
    [attachment release];
    return aString;
}
4

1 回答 1

4

由于附件由单个(不可见)字形 (0xFFFC) 组成,因此您可以使用字形消息来获取边界框。这是我用来根据鼠标位置突出显示 NSTextView 中的附件的代码(需要获取附件边界):

/**
 * Determines the index under the mouse. For highlighting we use the index only if the mouse is actually
 * within the tag bounds. For selection purposes we return the index as it was found even if the mouse pointer
 * is outside the tag bounds.
 */
- (NSUInteger)updateTargetDropIndexAtPoint: (NSPoint)point
{
    CGFloat fraction;
    NSUInteger index = [self.layoutManager glyphIndexForPoint: point
                                              inTextContainer: self.textContainer
                               fractionOfDistanceThroughGlyph: &fraction];
    NSUInteger caretIndex = index;
    if (fraction > 0.5) {
        caretIndex++;
    }

    // For highlighting a tag we need check if the mouse is actually within the tag.
    NSRect bounds = [self.layoutManager boundingRectForGlyphRange: NSMakeRange(index, 1)
                                                  inTextContainer: self.textContainer];
    NSUInteger newIndex;
    if (NSPointInRect(point, bounds)) {
        newIndex = index;
    } else {
        newIndex = NSNotFound;
    }
    if (hotTagIndex != newIndex) {
        NSRect oldBounds = [self.layoutManager boundingRectForGlyphRange: NSMakeRange(hotTagIndex, 1)
                                                         inTextContainer: self.textContainer];
        [self setNeedsDisplayInRect: oldBounds];
        hotTagIndex = newIndex;
        [self setNeedsDisplayInRect: bounds];
    }

    return caretIndex;
}

此代码用于 NSTextView 后代,因此 self.layoutManager 访问。

于 2013-04-07T09:56:33.837 回答