【问题标题】:CATextLayer and tracking / spacing between charactersCATextLayer 和字符之间的跟踪/间距
【发布时间】:2011-09-04 12:46:18
【问题描述】:

我正在使用 CATextLayer,为了在 iOS 中使用自定义字体,我知道有一种简单的方法可以通过 Fonts provided by application 使用自定义字体,但这是不同的字体。我想知道有没有办法改变每个字符之间的间距?我没有找到任何财产这样做!

已编辑:

- (void)viewWillAppear:(BOOL)animated {
    CTFontRef font = [self newCustomFontWithName:@"yeki" 
                                          ofType:@"ttf" 
                                      attributes:[NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:16.f] 
                                                                             forKey:(NSString *)kCTFontSizeAttribute]];


    CGRect screenBounds = [[UIScreen mainScreen] bounds];

    normalTextLayer_ = [[CATextLayer alloc] init];
    normalTextLayer_.font = font;
    normalTextLayer_.string = str;
    normalTextLayer_.wrapped = YES;
    normalTextLayer_.foregroundColor = [[UIColor purpleColor] CGColor];
    normalTextLayer_.fontSize = 50.f;
    normalTextLayer_.alignmentMode =  kCAAlignmentRight;

    normalTextLayer_.frame = CGRectMake(0.f,100.f, screenBounds.size.width, screenBounds.size.height /1.f);
    [self.view.layer addSublayer:normalTextLayer_];
    CFRelease(font);
}

【问题讨论】:

  • 你是说字距?您可以尝试使用CGContextSetCharacterSpacing
  • 是的,但我没有为 CATextLayer 类找到CGContextSetCharacterSpacing 的任何解决方案!

标签: iphone ios core-animation catextlayer


【解决方案1】:

您可以为图层分配NSAttributedString(或NSMutableAttributedString)而不是普通的NSString,并使用kCTKernAttributeName 属性(请参阅Core Text String Attributes Reference)来调整字距调整。

例子:

CTFontRef font = CTFontCreateWithName(CFSTR("Helvetica"), 30, NULL);
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                            (id)font, kCTFontAttributeName, 
                            [NSNumber numberWithFloat:15.0], kCTKernAttributeName, 
                            (id)[[UIColor greenColor] CGColor], kCTForegroundColorAttributeName, nil];
NSAttributedString *attributedString = [[[NSAttributedString alloc] initWithString:@"Hello World" attributes:attributes] autorelease];
CFRelease(font);
myTextLayer.string = attributedString;

这应该会在 Helvetica 30 中为您提供绿色文本,并增加字符间距。

【讨论】:

  • 谢谢。你能告诉我如何使用它:kCTKernAttributeName 因为当我用NSAttributedString 替换我的 CATextLayer 字符串时,我的文本失去了一些效果,如颜色、自定义字体等......
  • CATextLayer 的颜色和字体属性仅适用于纯字符串,因为NSAttributedString 定义了自己的属性,可以应用于字符串中的不同范围(不同的字符可以有不同的颜色... )。您可以使用initWithString:attributes 使用适用于整个字符串的属性字典来初始化属性字符串。有关可用属性的概述,请参阅我链接到的文档。
  • 对不起,我是小菜鸟,我收到了这个警告:Semantic Issue: Incompatible pointer types sending 'const CFStringRef' (aka 'const struct __CFString *const') to parameter of type 'id 如果你能告诉我怎么做,我将不胜感激
  • 添加了一个例子,希望对您有所帮助。
猜你喜欢
  • 2011-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-23
  • 1970-01-01
  • 1970-01-01
  • 2023-01-18
相关资源
最近更新 更多