gpt4 book ai didi

ios - 在 CATextLayer 中显示属性字符串

转载 作者:技术小花猫 更新时间:2023-10-29 11:18:56 24 4
gpt4 key购买 nike

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

#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 吗?我的属性设置错了吗?我完全走错了路吗?请注意,这适用于 iOS 5.x 应用程序,出于性能原因,我想使用 CATextLayer。真正的应用程序将有许多 CATextLayer

最佳答案

对于 kCTForegroundColorAttributeName,您必须使用 CGColor 而不是 UIColor:

[attributes setObject:(__bridge id)[UIColor blueColor].CGColor
forKey:(NSString *)kCTForegroundColorAttributeName];

关于ios - 在 CATextLayer 中显示属性字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16052863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com