【发布时间】:2011-01-13 15:54:11
【问题描述】:
是否可以将UILabel 添加到CALayer 而无需子类化并在drawInContext: 中绘制它?
谢谢!
【问题讨论】:
标签: iphone
是否可以将UILabel 添加到CALayer 而无需子类化并在drawInContext: 中绘制它?
谢谢!
【问题讨论】:
标签: iphone
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];
【讨论】:
我认为您不能将 UIView 子类添加到 CALayer 对象。但是,如果您想在 CALayer 对象上绘制文本,可以使用 NSString UIKit additions 中提供的绘制函数来完成,如下所示。虽然我的代码是在委托的 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();
}
【讨论】:
只是为了记录我的方法,我在 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
【讨论】:
你的 UILabel 后面已经有一个 CALayer。如果您将多个 CALayer 放在一起,您只需将 UILabel 的层添加为其中一个的子层(通过使用其layer 属性)。
如果在您想要的图层中直接绘制文本,那么 Deepak 指向的 UIKit NSString 附加项就是您要走的路。例如,Core Plot framework 有一个独立于 Mac / iPhone 平台的 CALayer 子类,它执行文本渲染,CPTextLayer。
【讨论】:
添加一个 CATextLayer 作为子层并设置字符串属性。这将是最简单的,您可以轻松地使用布局管理器使其非常通用。
【讨论】:
下面的答案很好,只要确保你添加,否则你的文字会模糊:
textLayer.contentsScale = UIScreen.main.scale
Swift 的最终代码:
let textLayer = CATextLayer()
textLayer.frame = CGRect(x: 0, y: 0, width: 60, height: 15)
textLayer.fontSize = 12
textLayer.string = "my text"
textLayer.foregroundColor = UIColor.red.cgColor
textLayer.contentsScale = UIScreen.main.scale
【讨论】:
如果要添加另一个子层,请务必记住删除以前的子层,以防止重复视图:
if let sublayers = layer.sublayers {
for sublayer in sublayers {
sublayer.removeFromSuperlayer()
}
}
【讨论】: