【问题标题】:How to get the path Quartz is using to stroke a NSBezierPath如何获取 Quartz 用来描边 NSBezierPath 的路径
【发布时间】:2012-07-09 19:22:56
【问题描述】:

我正在使用此代码用一条宽的黑色虚线描边 NSBezierPath。

cstrForBezier 在其他地方定义)

NSGlyph glyph;
for(n = 0; n < len; n++) {
    glyph = [font glyphWithName: [strForBezier substringWithRange:NSMakeRange(n, 1)]];
    [path appendBezierPathWithGlyph: glyph inFont: font];
}

CGFloat pattern2[4]; pattern2[0]=5*c; pattern2[1]=2*c; pattern2[2]=2*c; pattern2[3]=2*c;
[path setLineDash:pattern2 count:4 phase:0];

[path setLineWidth:c];
[path stroke];
[[NSColor blueColor] set ];
[path fill];

我怎样才能得到黑色的 NSBezierPath ?我假设 NSBezierPath 已构建并填充以描边初始曲线。

【问题讨论】:

    标签: cocoa cgpath nsbezierpath


    【解决方案1】:

    您可以通过划线和抚摸现有路径来创建路径,但这需要使用CGPathRef 而不是NSBezierPath

    CGMutablePathRef path0 = CGPathCreateMutable();
    CGAffineTransform transform = CGAffineTransformMakeTranslation(20, 20);
    // initial position is {20, 20}
    
    CGGlyph glyph;
    for(n = 0; n < len; n++)
    {
        glyph = [font glyphWithName: [strForBezier substringWithRange:NSMakeRange(n, 1)]];
        CGPathRef glyphPath = CTFontCreatePathForGlyph((__bridge CTFontRef) font, glyph, NULL);
        CGPathAddPath(path0, &transform, glyphPath);
        CGPathRelease(glyphPath);
    
        // append the glyph advance to the transform
        CGSize advance;
        CTFontGetAdvancesForGlyphs((__bridge CTFontRef) font, kCTFontDefaultOrientation, &glyph, &advance, 1);
        transform.tx += advance.width;
        transform.ty += advance.height;
    }
    
    CGFloat pattern2[4]; pattern2[0]=5*c; pattern2[1]=2*c; pattern2[2]=2*c; pattern2[3]=2*c;
    CGPathRef path1 = CGPathCreateCopyByDashingPath(path0, NULL, 0, pattern2, 4);
    CGPathRef path2 = CGPathCreateCopyByStrokingPath(path1, NULL, c, kCGLineCapButt, kCGLineJoinMiter, CGFLOAT_MAX);
    
    CGContextRef context = [NSGraphicsContext currentContext].graphicsPort;
    CGContextAddPath(context, path2);
    CGContextDrawPath(context, kCGPathFill);
    
    CGPathRelease(path0);
    CGPathRelease(path1);
    CGPathRelease(path2);
    

    如果您对CGPathRef 不满意,您可以创建一个NSBezierPath,然后使用Apple 文档Building a CGPathRef From a NSBezierPath Object 中描述的方法将其转换为CGPathRef(也可以反过来)。

    【讨论】:

    • 代码有意义,但我无法在我的系统上编译它(OS X 10.7);我有 1/Use of undeclared identifier 'kCTFontOrientationDefault'; did you mean 'kCTFontOptionsDefault'? 2/Incompatible pointer types passing 'NSGlyph *' (aka 'unsigned int *') to parameter of type 'const CGGlyph *' (aka 'const unsigned short *')
    • 我通过使用 CGGlyph 而不是 NSGlyph 修复了指针类型问题(尽管它们存储相同的值,但它们的大小不同)。 kCTFontOrientationDefault 应该被声明。您可能需要包含 &lt;CoreText/CoreText.h&gt; 标头。
    • kCTFontOrientationDefault 未定义。正确的名称是:kCTFontDefaultOrientation
    • 我的错。你是对的:kCTFontDefaultOrientation 是正确的名称,kCTFontOrientationDefault 尚未声明。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 2012-03-28
    • 2020-02-07
    相关资源
    最近更新 更多