CALayer和CATextLayer之间的垂直对齐

时间:2017-10-21 18:41:40

标签: ios objective-c calayer


我目前正在使用CALayer和CATextLayer,在垂直对齐时我遇到了困难。
我创建了一个用于在其中显示图像的CALayer,然后在计算CATexLayer的文本大小后在CALayer下面添加CATextLayer,您可以查看我的代码以获取更多详细信息:

+ (instancetype)itemWithImage:(UIImage *)image andTitle:(NSString *)title {
    CGSize size = CGSizeMake(MIN(image.size.width, [XFATLayoutAttributes itemWidth]), MIN(image.size.height, [XFATLayoutAttributes itemWidth]));
    CALayer *layer = [CALayer layer];
    layer.contents = (__bridge id)image.CGImage;
    layer.bounds = CGRectMake(0, 0, MIN(size.width, [XFATLayoutAttributes itemImageWidth]), MIN(size.height, [XFATLayoutAttributes itemImageWidth]));

    CATextLayer *label = [[CATextLayer alloc] init];
    [label setFont:@"Helvetica"];
    [label setFontSize:14];
    label.alignmentMode = kCAAlignmentCenter;

    label.backgroundColor = [UIColor redColor].CGColor;
    label.string = title;
    label.foregroundColor = [UIColor colorWithRed:138/255.0 green:138/255.0 blue:143/255.0 alpha:1.0].CGColor;
    label.wrapped = YES;
    label.contentsScale = [UIScreen mainScreen].scale;

    CGSize stringSize = [title sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:14.0]}];
    label.frame = CGRectMake(-5, layer.bounds.size.height + 5, stringSize.width, stringSize.height + 1);

    [layer addSublayer:label];

    return [[self alloc] initWithLayer:layer];
}

但问题是文字大小不一样,而且我的CATextLayer错位有点像这张图片: enter image description here

如何在X轴上对齐它们?请帮忙。
提前谢谢。

1 个答案:

答案 0 :(得分:1)

您可以这样计算右X偏移:

label.frame = CGRectMake((size.width - stringSize.width) / 2, layer.bounds.size.height + 5,
                         stringSize.width, stringSize.height + 1);

或者您可以简单地将label宽度设置为image宽度,因为您将文字与中心对齐:

label.frame = CGRectMake(0, layer.bounds.size.height + 5,
                             size.width, stringSize.height + 1);

BTW我无法使用return [[self alloc] initWithLayer:layer]使用你的方法,所以我不得不返回构造的子类实例本身:

AlignLayer *layer = [AlignLayer layer]; // my subclass
// ...
return layer;

Apple warns反对在这种情况下使用initWithLayer:

  

此初始值设定项用于创建图层的阴影副本,例如,用于presentationLayer方法。在任何其他情况下使用此方法将产生未定义的行为。 例如,请勿使用此方法初始化具有现有图层内容的新图层