我想在UIView上的子类上绘制文本,以便从文本中剪切出文本,并在视图后面显示背景,就像在此处找到的OSX Mavericks徽标一样.
我会说我更像是一个中级/早期的高级iOS开发人员,所以请随意向我提出一些疯狂的解决方案.我希望我必须覆盖drawRect
才能做到这一点.
多谢你们!
编辑:
我应该提一下,我的第一次尝试是使文本[UIColor clearColor]
无效,因为只是将文本的alpha分量设置为0,这只是通过文本显示视图.
Sta*_*ort 18
免责声明:我是在没有测试的情况下写的,所以请原谅我,如果我错在这里.
您应该通过以下两个步骤实现所需:
创建CATextLayer
你的看法的大小,设置backgroundColor
是完全透明的,foregroundColor
是不透明的(由[UIColor colorWithWhite:0 alpha:1]
和[UIColor colorWithWhite:0 alpha:0]
,然后设置string
属性要呈现的字符串,font
并fontSize
等
将视图的图层蒙版设置为此图层:myView.layer.mask = textLayer
.您必须导入QuartzCore
才能访问CALayer
视图.
请注意,我可能在第一步中在不透明和透明颜色之间切换.
编辑:的确,诺亚是对的.为了克服这个问题,我使用了CoreGraphics和kCGBlendModeDestinationOut
混合模式.
首先,示例视图显示它确实有效:
@implementation TestView
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.backgroundColor = [UIColor clearColor];
}
return self;
}
- (void)drawRect:(CGRect)rect {
[[UIColor redColor] setFill];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:10];
[path fill];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context); {
CGContextSetBlendMode(context, kCGBlendModeDestinationOut);
[@"Hello!" drawAtPoint:CGPointZero withFont:[UIFont systemFontOfSize:24]];
} CGContextRestoreGState(context);
}
@end
Run Code Online (Sandbox Code Playgroud)
添加以下内容到视图控制器后,你会看到背后的看法TestView
,其中Hello!
绘制.
为什么这样做:
混合模式定义为R = D*(1 - Sa)
,意味着我们需要与mask
之前建议的层相反的alpha值.因此,您需要做的就是使用不透明的颜色进行绘制,这将从您事先在视图上绘制的内容中减去.
归档时间: |
|
查看次数: |
5675 次 |
最近记录: |