我有一个带有图像的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;
}
答案 0 :(得分:3)
由于附件由单个(不可见)字形(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。