我有一个带有图像的 NSTextView。我想为这些图像添加跟踪区域。我需要包含图像的单元格框架来创建跟踪区域。
所以我的问题是:如何在 NSTextView 的坐标系中获取 NSTextAttachments 的框架?
我正在以编程方式更改 TextView 中图像的大小,此时我需要创建这个新的跟踪区域。我正在执行以下操作以创建带有文本附件的属性字符串,然后以编程方式将其插入到我的 TextView 的属性字符串中。但是一旦完成所有这些操作,我就不知道如何为新附件创建跟踪区域了。
-(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;
}
最佳答案
由于附件由单个(不可见)字形 (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。
关于objective-c - 在 NSTextView 中获取 NSTextAttachmentCell 的框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14787258/