我只是想在UIView层中添加一个CATextlayer。但是,根据下面的代码,我只获得了要在UIView中显示的CATextlayer的背景色,而没有显示任何文本。
谁能提供一个如何使用CATextlayer的提示/示例
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
CATextLayer *TextLayer = [CATextLayer layer];
TextLayer.bounds = CGRectMake(0.0f, 0.0f, 100.0f, 100.0f);
TextLayer.string = @"Test";
TextLayer.font = [UIFont boldSystemFontOfSize:18].fontName;
TextLayer.backgroundColor = [UIColor blackColor].CGColor;
TextLayer.wrapped = NO;
//TextLayer.backgroundColor = [UIColor blueColor];
self.view = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
self.view.backgroundColor = [UIColor blueColor];
[self.view.layer addSublayer:TextLayer];
[self.view.layer layoutSublayers];
}
return self;
}发布于 2013-05-03 20:34:16
对于iOS 5及更高版本,可以按如下方式使用CATextLayer:
CATextLayer *textLayer = [CATextLayer layer];
textLayer.frame = CGRectMake(144, 42, 76, 21);
textLayer.font = CFBridgingRetain([UIFont boldSystemFontOfSize:18].fontName);
textLayer.fontSize = 18;
textLayer.foregroundColor = [UIColor redColor].CGColor;
textLayer.backgroundColor = [UIColor yellowColor].CGColor;
textLayer.alignmentMode = kCAAlignmentCenter;
textLayer.string = @"BAC";
[self.view.layer addSublayer:textLayer];您可以将此代码添加到您喜欢的任何函数中。特别是在这里,字体的正确分配是必要的,否则无论您设置什么textColor,您的CATextLayer都将呈现为黑色。
发布于 2010-07-23 06:08:56
将您的代码更改为:
CATextLayer *TextLayer = [CATextLayer layer];
TextLayer.bounds = CGRectMake(0.0f, 0.0f, 100.0f, 100.0f);
TextLayer.string = @"Test";
TextLayer.font = [UIFont boldSystemFontOfSize:18].fontName;
TextLayer.backgroundColor = [UIColor blackColor].CGColor;
TextLayer.position = CGPointMake(80.0, 80.0f);
TextLayer.wrapped = NO;
[self.view.layer addSublayer:TextLayer];您还应该在视图控制器的-viewDidLoad中执行此操作。这样,您就知道视图已加载且有效,并且现在可以向其中添加层。
发布于 2016-08-09 01:30:43
斯威夫特
下面的示例显示了一个带有CATextLayer的视图,该视图使用带有彩色文本的自定义字体。

import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Attributed string
let myAttributes = [
NSFontAttributeName: UIFont(name: "Chalkduster", size: 30.0)! , // font
NSForegroundColorAttributeName: UIColor.cyanColor() // text color
]
let myAttributedString = NSAttributedString(string: "My text", attributes: myAttributes )
// Text layer
let myTextLayer = CATextLayer()
myTextLayer.string = myAttributedString
myTextLayer.backgroundColor = UIColor.blueColor().CGColor
myTextLayer.frame = myView.bounds
myView.layer.addSublayer(myTextLayer)
}
} 我更完整的回答是here。
https://stackoverflow.com/questions/3068335
复制相似问题