小智 148
CATextLayer *label = [[CATextLayer alloc] init];
[label setFont:@"Helvetica-Bold"];
[label setFontSize:20];
[label setFrame:validFrame];
[label setString:@"Hello"];
[label setAlignmentMode:kCAAlignmentCenter];
[label setForegroundColor:[[UIColor whiteColor] CGColor]];
[layer addSublayer:label];
[label release];
Run Code Online (Sandbox Code Playgroud)
Dee*_*olu 38
我不认为你可以将一个UIView子类添加到CALayer对象.但是,如果要在CALayer对象上绘制文本,可以使用NSString UIKit 添加中提供的绘图功能来完成,如下所示.虽然我的代码是在委托的drawLayer:inContext方法中完成的,但同样可以在子类'drawInContext:方法中使用.您是否想要利用任何特定的UILabel功能?
- (void) drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
CGContextSetFillColorWithColor(ctx, [[UIColor darkTextColor] CGColor]);
UIGraphicsPushContext(ctx);
/*[word drawInRect:layer.bounds
withFont:[UIFont systemFontOfSize:32]
lineBreakMode:UILineBreakModeWordWrap
alignment:UITextAlignmentCenter];*/
[word drawAtPoint:CGPointMake(30.0f, 30.0f)
forWidth:200.0f
withFont:[UIFont boldSystemFontOfSize:32]
lineBreakMode:UILineBreakModeClip];
UIGraphicsPopContext();
}
Run Code Online (Sandbox Code Playgroud)
只是为了记录我的方法,我在 Swift 4+ 中这样做了:
let textlayer = CATextLayer()
textlayer.frame = CGRect(x: 20, y: 20, width: 200, height: 18)
textlayer.fontSize = 12
textlayer.alignmentMode = .center
textlayer.string = stringValue
textlayer.isWrapped = true
textlayer.truncationMode = .end
textlayer.backgroundColor = UIColor.white.cgColor
textlayer.foregroundColor = UIColor.black.cgColor
caLayer.addSublayer(textlayer) // caLayer is and instance of parent CALayer
Run Code Online (Sandbox Code Playgroud)
您的 UILabel 背后已经有一个 CALayer。如果您将多个 CALayer 放在一起,则可以将 UILabel 的图层添加为其中一个的子图层(通过使用其layer
属性)。
如果是在您想要的图层中直接绘制文本,Deepak 指向的 UIKit NSString 添加是要走的路。例如,Core Plot 框架有一个独立于 Mac/iPhone 平台的 CALayer 子类,它执行文本渲染,CPTextLayer。
归档时间: |
|
查看次数: |
40864 次 |
最近记录: |