你如何抚摸NSAttributedString的_outside_?

Tom*_*ing 13 cocoa objective-c nsattributedstring

我一直在使用NSStrokeWidthAttributeNameNSAttributedString对象,因为它是画把大纲文本周围.问题是笔划位于文本的填充区域内.当文本很小(例如1像素厚)时,抚摸使文本难以阅读.我真正想要的是外面的中风.有没有办法做到这一点?

我试过NSShadow没有偏移和模糊,但它太模糊,很难看到.如果有办法增加阴影的大小而没有任何模糊,那也可以.

NSG*_*God 33

虽然可能有其他方法,但实现此目的的一种方法是首先仅使用笔划绘制字符串,然后仅使用填充绘制字符串,直接覆盖先前绘制的字符串.(Adobe InDesign实际上有这种内置功能,它似乎只将笔划应用于字母外部,这有助于提高可读性).

这只是一个示例视图,展示了如何实现这一目标(受http://developer.apple.com/library/mac/#qa/qa2008/qa1531.html启发):

首先设置属性:

@implementation MDInDesignTextView

static NSMutableDictionary *regularAttributes = nil;
static NSMutableDictionary *indesignBackgroundAttributes = nil;
static NSMutableDictionary *indesignForegroundAttributes = nil;

- (void)drawRect:(NSRect)frame {
    NSString *string = @"Got stroke?";
    if (regularAttributes == nil) {
        regularAttributes = [[NSMutableDictionary
    dictionaryWithObjectsAndKeys:
        [NSFont systemFontOfSize:64.0],NSFontAttributeName,
        [NSColor whiteColor],NSForegroundColorAttributeName,
        [NSNumber numberWithFloat:-5.0],NSStrokeWidthAttributeName,
        [NSColor blackColor],NSStrokeColorAttributeName, nil] retain];
    }

    if (indesignBackgroundAttributes == nil) {
        indesignBackgroundAttributes = [[NSMutableDictionary
        dictionaryWithObjectsAndKeys:
        [NSFont systemFontOfSize:64.0],NSFontAttributeName,
        [NSNumber numberWithFloat:-5.0],NSStrokeWidthAttributeName,
        [NSColor blackColor],NSStrokeColorAttributeName, nil] retain];
    }

    if (indesignForegroundAttributes == nil) {
        indesignForegroundAttributes = [[NSMutableDictionary
        dictionaryWithObjectsAndKeys:
        [NSFont systemFontOfSize:64.0],NSFontAttributeName,
        [NSColor whiteColor],NSForegroundColorAttributeName, nil] retain];
    }

    [[NSColor grayColor] set];
    [NSBezierPath fillRect:frame];

    // draw top string
    [string drawAtPoint:
        NSMakePoint(frame.origin.x + 200.0, frame.origin.y + 200.0)
        withAttributes:regularAttributes];

    // draw bottom string in two passes
    [string drawAtPoint:
        NSMakePoint(frame.origin.x + 200.0, frame.origin.y + 140.0)
        withAttributes:indesignBackgroundAttributes];
    [string drawAtPoint:
        NSMakePoint(frame.origin.x + 200.0, frame.origin.y + 140.0)
        withAttributes:indesignForegroundAttributes];
}

@end
Run Code Online (Sandbox Code Playgroud)

这会产生以下输出:

替代文字

替代文字

现在,它并不完美,因为字形有时会落在小数边界上,但它看起来肯定比默认值更好.

如果性能是一个问题,您可以随时考虑降低到稍低的级别,例如CoreGraphics或CoreText.

  • 简单的。杰出的。...并且应该完全没有必要...(对此应该已经存在支持) (2认同)