9

我有一个简单的示例应用程序,我在其中创建 aCATextLayer并将其string属性设置为NSAttributedString. 然后我将该 CATextLayer 添加到视图中。

#import <CoreText/CoreText.h>
#import <QuartzCore/QuartzCore.h>

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    CTFontRef fontFace = CTFontCreateWithName((__bridge CFStringRef)(@"HelfaSemiBold"), 24.0, NULL);
    NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
    [attributes setObject:(__bridge id)fontFace forKey:(NSString*)kCTFontAttributeName];
    [attributes setObject:[UIColor blueColor] forKey:(NSString*)kCTForegroundColorAttributeName];
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:@"Lorem Ipsum" attributes:attributes];

    CATextLayer *textLayer = [CATextLayer layer];
    textLayer.backgroundColor = [UIColor whiteColor].CGColor;
    textLayer.frame = CGRectMake(20, 20, 200, 100);
    textLayer.contentsScale = [[UIScreen mainScreen] scale];
    textLayer.string = attrStr;

    [self.view.layer addSublayer:textLayer];
}

这在模拟器中效果很好,除了文本是黑色而不是蓝色。在设备上运行时,一切都像在模拟器上一样显示,但它会在控制台中生成以下两个错误。

<Error>: CGContextSetFillColorWithColor: invalid context 0x0
<Error>: CGContextSetStrokeColorWithColor: invalid context 0x0

我应该在某处设置 CGContext 吗?我是否设置了错误的属性?我是不是完全走错了路。CATextLayer请注意,这适用于 iOS 5.x 应用程序,出于性能原因,我想使用 a 。真正的应用程序会有很多 CATextLayers。

4

2 回答 2

12

您必须使用CGColor而不是UIColorfor kCTForegroundColorAttributeName

[attributes setObject:(__bridge id)[UIColor blueColor].CGColor
               forKey:(NSString *)kCTForegroundColorAttributeName];
于 2013-04-17T06:38:51.593 回答
0

我将其转换为 Swift 3 并将其也放入 SpriteKit 中:

import QuartzCore
import SpriteKit

class GameScene: SKScene {

  var textLayer = CATextLayer()

  func helloWord() {
    let fontFace = CTFontCreateWithName((("HelfaSemiBold") as CFString),
                                        24.0,
                                        nil)
    var attributes: [AnyHashable: Any]? = [:]
    attributes?[(kCTFontAttributeName as String)] = fontFace
    attributes?[(kCTForegroundColorAttributeName as String)] = UIColor.blue.cgColor

    let attrStr = NSAttributedString(string: "Hello Attributed Word!",
                                     attributes: attributes as! [String : Any]?)

    textLayer.backgroundColor = UIColor.white.cgColor
    textLayer.frame = CGRect(x: CGFloat(50), y: CGFloat(200),
                             width: CGFloat(300), height: CGFloat(100))
    textLayer.contentsScale = UIScreen.main.scale
    textLayer.string = attrStr
    self.view?.layer.addSublayer(textLayer)
  }

  override func didMove(to view: SKView) {
    helloWord()
  }
}
于 2016-12-08T16:00:09.693 回答