Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CATextLayer and tracking / spacing between characters

I am using CATextLayer , in order to using a custom font in iOS , I know there is simple way to using custom font with Fonts provided by application but this is different font . I was wondering is there any way to change the spacing between each characters ? I did not find any property to do so !

EDITED :

- (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);
}
like image 502
iOS.Lover Avatar asked Sep 04 '11 12:09

iOS.Lover


1 Answers

You can assign an NSAttributedString (or NSMutableAttributedString) instead of a plain NSString to the layer and use the kCTKernAttributeName attribute (see Core Text String Attributes Reference) to adjust the kerning.

Example:

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;

That should give you green text in Helvetica 30 with increased character spacing.

like image 72
omz Avatar answered Oct 02 '22 00:10

omz