如何在drawLayer:inContext委托中绘制既有描边又有填充的文本。

3
这是我在的委托中的方法。
它只负责绘制一个长度为1的字符串。
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx 
    {
        CGRect boundingBox = CGContextGetClipBoundingBox(ctx);
        NSAttributedString *string = [[NSAttributedString alloc] initWithString:self.letter attributes:[self attrs]];

        CGContextSaveGState(ctx);

        CGContextSetShadowWithColor(ctx, CGSizeZero, 3.0, CGColorCreateGenericRGB(1.0, 1.0, 0.922, 1.0));
        CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)string);
        CGRect rect = CTLineGetImageBounds(line, ctx);
        CGFloat xOffset = CGRectGetMidX(rect);
        CGFloat yOffset = CGRectGetMidY(rect);
        CGPoint pos = CGPointMake(CGRectGetMidX(boundingBox) - xOffset, CGRectGetMidY(boundingBox)- yOffset);
        CGContextSetTextPosition(ctx, pos.x, pos.y);

        CTLineDraw(line, ctx);

    CGContextRestoreGState(ctx);
}

这是属性字典:

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
[NSFont fontWithName:@"GillSans-Bold" size:72.0], NSFontAttributeName,
[NSColor blackColor], NSForegroundColorAttributeName,
[NSNumber numberWithFloat:1.0], NSStrokeWidthAttributeName,
[NSColor blackColor], NSStrokeColorAttributeName,
style, NSParagraphStyleAttributeName, nil];

目前情况是,描边无法绘制,只有填充能够绘制。

如果我在字典中注释掉描边属性,那么填充就能绘制。

我知道这不可能是正确的,但我找不到任何关于这个问题的参考资料。

在使用委托绘制文本时,是否存在已知问题?

由于字符串只有一个字符,所以我按照文档示例未使用任何framesetter机制,但仍尝试过这种方法以解决问题,但没有成功。

1个回答

3
在阅读这个问题的答案时,我意识到需要使用负数作为描边值。我一直认为描边应该应用于由CTLineDraw绘制的字母外部,而不是文本形状内部。
为了帮助其他遇到同样误解的人,我自己回答了这个问题,因为我没有看到参考文档涵盖了这一点。

这个负数的评论真的帮了我很多。非常感谢你。 - Piotr Tomasik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接