如何获取Quartz用于描边NSBezierPath的路径

时间:2012-07-09 19:22:56

标签: cocoa cgpath nsbezierpath

A dashed line

我正在使用此代码使用宽的虚线黑线描边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以描绘初始曲线。

1 个答案:

答案 0 :(得分:3)

您可以通过划线和抚摸现有路径来创建路径,但这需要使用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感到不舒服,可以使用Apple文档Building a CGPathRef From a NSBezierPath Object中描述的方法创建NSBezierPath,然后将其转换为CGPathRef。也是可能的。)