Question

I am trying to bring my CATextLayer text (which is a number "1") in center of view, but what I got is very small text and not in center as shown in this image. Red circle shown is a CALayer object itself which is animated, so I dont want to add text as sublayer to it. Instead I added as sublayer to view. The code I wrote for CATextLayer is:

CATextLayer *numbers = [CATextLayer layer];

numbers.string = @"1";
numbers.font = [UIFont fontWithName:@"Arial" size:100.0];
numbers.foregroundColor = [UIColor blackColor].CGColor;
numbers.bounds = CGRectMake(0, 0, 200, 200);
numbers.position = self.view.center;
numbers.wrapped = NO;

[self.view.layer addSublayer:numbers];

I hope my Question is clear. Please tell me where am I mistaken? Thanks alot.

Was it helpful?

Solution

Edit

The font property takes a CGFontRef and not a UIFont. You can create one using CGFontCreateWithFontName( (CFStringRef)@"ArialMT" ). The font size is set using the fontSize property.

Original answer

The correct font name is "ArialMT"1. Since you are using a non-existing font name the text gets the default font and size.

The layer is in fact centered and 200 by 200 points2. The problem is that the text is not centered inside the text layer, instead the text is in the upper left corner. A bigger font could make it look like it's almost centered but it still wouldn't be.

You can change how the content of the layer (in your case the text) is drawn relative to the bounds of the layer by changing the contentsGravity of the layer to something like kCAGravityCenter if you want the text to appear centered inside the frame of the text layer


  1. iOS Fonts is a great resource for the names you should use to get certain fonts.
  2. This can easily be verified by giving the text layer a strong background color like clear blue (since your circle is red)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top