在NSTextView中显示隐藏的字符

tit*_*coy 6 cocoa special-characters hidden-characters

我正在为Mac OS X编写一个文本编辑器.我需要在NSTextView中显示隐藏的字符(例如空格,制表符和特殊字符).我花了很多时间寻找如何做到这一点,但到目前为止我还没有找到答案.如果有人能指出我正确的方向,我将不胜感激.

Pol*_*Pol 9

这是一个完全工作和干净的实现

@interface GILayoutManager : NSLayoutManager
@end

@implementation GILayoutManager

- (void)drawGlyphsForGlyphRange:(NSRange)range atPoint:(NSPoint)point {
  NSTextStorage* storage = self.textStorage;
  NSString* string = storage.string;
  for (NSUInteger glyphIndex = range.location; glyphIndex < range.location + range.length; glyphIndex++) {
    NSUInteger characterIndex = [self characterIndexForGlyphAtIndex: glyphIndex];
    switch ([string characterAtIndex:characterIndex]) {

      case ' ': {
        NSFont* font = [storage attribute:NSFontAttributeName atIndex:characterIndex effectiveRange:NULL];
        [self replaceGlyphAtIndex:glyphIndex withGlyph:[font glyphWithName:@"periodcentered"]];
        break;
      }

      case '\n': {
        NSFont* font = [storage attribute:NSFontAttributeName atIndex:characterIndex effectiveRange:NULL];
        [self replaceGlyphAtIndex:glyphIndex withGlyph:[font glyphWithName:@"carriagereturn"]];
        break;
      }

    }
  }

  [super drawGlyphsForGlyphRange:range atPoint:point];
}

@end
Run Code Online (Sandbox Code Playgroud)

要安装,请使用:

[myTextView.textContainer replaceLayoutManager:[[GILayoutManager alloc] init]];
Run Code Online (Sandbox Code Playgroud)

要查找字体字形名称,您必须转到CoreGraphics:

CGFontRef font = CGFontCreateWithFontName(CFSTR("Menlo-Regular"));
for (size_t i = 0; i < CGFontGetNumberOfGlyphs(font); ++i) {
  printf("%s\n", [CFBridgingRelease(CGFontCopyGlyphNameForGlyph(font, i)) UTF8String]);
}
Run Code Online (Sandbox Code Playgroud)


e.J*_*mes 5

看看 NSLayoutManager 类。您的 NSTextView 将有一个与之关联的布局管理器,布局管理器负责将字符(空格、制表符等)与字形(在屏幕上绘制的该字符的图像)相关联。

在您的情况下,您可能对replaceGlyphAtIndex:withGlyph:方法最感兴趣,它允许您替换单个字形。