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

标签 ios drawing core-graphics clipping

在 Core Graphics 中创建填充路径非常简单,就像创建填充文本一样。但是我还没有找到除了子路径中的文本之外的路径示例。我对文本绘制模式、剪裁等方面的实验毫无进展。

这是一个示例(在 photoshop 中创建)。您将如何在 Core Graphics 中创建前景形状?

Example of text subtracted from path (created in photoshop)

我要提到的是,这项技术似乎在即将推出的主要移动操作系统版本中大量使用,但我不想与 SO 的 NDA-police 发生冲突;)

最佳答案

这是我运行并测试过的一些代码,它们对您有用。有关详细信息,请参阅内联评论:

更新:我删除了 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);
}

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

Result

关于ios - 使用 Core Graphics 绘制带有减去文本的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18716751/

相关文章:

ios - 在节点模块中对 native 重建 .bin 文件夹使用react

ios - 如何访问存储在数组中的对象的数据?

javascript - Three.js:无法使用 THREE.ExtrudeGeometry 打洞(切割)线形状

ios - 绘制完美的圆角线,Swift

ios - 遍历 UnsafeMutableRawPointer 图像数据

ios - 为什么从模态视图返回时会触发 UIKeyboardDidShowNotification/UIKeyboardWillHideNotification?

ios - 获取隐式中心值 Titanium

java - Java 中的处理 - 调用方法后绘制的清除矩形会中断

xcode - 使用 1000 多个数据点在 Swift 中绘制折线图

ios - 将颜色加深限制在 CGPath 的内部