在 Core Graphics 中创建填充路径非常简单,就像创建填充文本一样。但是我还没有找到除了子路径中的文本之外的路径示例。我对文本绘制模式、剪裁等方面的实验毫无进展。
这是一个示例(在 photoshop 中创建)。您将如何在 Core Graphics 中创建前景形状?
我要提到的是,这项技术似乎在即将推出的主要移动操作系统版本中大量使用,但我不想与 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);
}
结果如下(您可以将背景更改为任何内容,您仍然可以看穿文本):
关于ios - 使用 Core Graphics 绘制带有减去文本的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18716751/