Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set CATextLayer text vertical position?

I create UILabel and CATextLayer in my app using following code

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.textLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 90, 20, 20)];
    self.textLabel.text = @"1";
    self.textLabel.font = [UIFont systemFontOfSize:12];
    self.textLabel.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.textLabel];

    self.textLayer = [CATextLayer layer];
    [self.textLayer setString:@"1"];
    [self.textLayer setFont:(__bridge CFTypeRef)([UIFont systemFontOfSize:12])];
    self.textLayer.backgroundColor = [UIColor greenColor].CGColor;
    self.textLayer.frame = CGRectMake(70, 90, 50, 20);
    [self.view.layer addSublayer:self.textLayer];
}

and the result is

enter image description here

The red one is UILabel, the green one is CALayer. I want to know how to vertical align the text inCALayer, as theUILabel` shows.

like image 328
NOrder Avatar asked Aug 08 '13 09:08

NOrder


1 Answers

Actually, this is what works for me:

self.layer.addSublayer(textLayer)
textLayer.font = font
textLayer.fontSize = font.pointSize
textLayer.frame = CGRectMake(self.layer.bounds.origin.x, ((self.layer.bounds.height - textLayer.fontSize) / 2) - lineWidth, self.layer.bounds.width, self.layer.bounds.height)
textLayer.alignmentMode - kCAAlignmentCenter
textLayer.contentsScale = UIScreen.mainScreen().scale

LineWidth is what I use to "frame" my bounding area. This keeps my text centered vertically and horizontally.

like image 87
BonanzaDriver Avatar answered Sep 30 '22 11:09

BonanzaDriver