使用Core Graphics绘制带减去文本的路径

Jay*_*ais 7 drawing clipping core-graphics ios

在Core Graphics中创建填充路径是直截了当的,就像创建填充文本一样.但是我还没有找到路径填充的路径示例,除了子路径中的文本.我的文本绘图模式,剪辑等实验让我无处可去.

这是一个例子(在photoshop中创建).你将如何在Core Graphics中创建前景形状?

从路径中减去的文本示例(在photoshop中创建)

我想提一下,这种技术似乎在即将推出的主流移动操作系统中大量使用,但我不想与SO的NDA警察发生冲突;)

Chr*_*nzo 12

这是我运行和测试的一些代码,对你有用.有关详细信息,请参阅内联注释:

更新:我已删除manualYOffset:参数.它现在进行计算以使文本在圆圈中垂直居中.请享用!

- (void)drawRect:(CGRect)rect {
    // Make sure the UIView's background is set to clear either in code or in a storyboard/nib

    CGContextRef context = UIGraphicsGetCurrentContext();

    [[UIColor whiteColor] setFill];
    CGContextAddArc(context, CGRectGetMidX(rect), CGRectGetMidY(rect), CGRectGetWidth(rect)/2, 0, 2*M_PI, YES);
    CGContextFillPath(context);

    // Manual offset may need to be adjusted depending on the length of the text
    [self drawSubtractedText:@"Foo" inRect:rect inContext:context];
}

- (void)drawSubtractedText:(NSString *)text inRect:(CGRect)rect inContext:(CGContextRef)context {
    // Save context state to not affect other drawing operations
    CGContextSaveGState(context);

    // Magic blend mode
    CGContextSetBlendMode(context, kCGBlendModeDestinationOut);

    // This seemingly random value adjusts the text
    // vertically so that it is centered in the circle.
    CGFloat Y_OFFSET = -2 * (float)[text length] + 5;

    // Context translation for label
    CGFloat LABEL_SIDE = CGRectGetWidth(rect);
    CGContextTranslateCTM(context, 0, CGRectGetHeight(rect)/2-LABEL_SIDE/2+Y_OFFSET);

    // Label to center and adjust font automatically
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, LABEL_SIDE, LABEL_SIDE)];
    label.font = [UIFont boldSystemFontOfSize:120];
    label.adjustsFontSizeToFitWidth = YES;
    label.text = text;
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor clearColor];
    [label.layer drawInContext:context];

    // Restore the state of other drawing operations
    CGContextRestoreGState(context);
}
Run Code Online (Sandbox Code Playgroud)

这是结果(您可以将背景更改为任何内容,您仍然可以查看文本):

结果