gpt4 book ai didi

ios - CALayer 和 CATextLayer 之间的垂直对齐

转载 作者:行者123 更新时间:2023-11-29 00:09:41 25 4
gpt4 key购买 nike


我目前正在使用 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 轴上对齐它们?请帮忙。
提前致谢。

最佳答案

您可以这样计算右 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);

顺便说一句,我无法使用 return [[self alloc] initWithLayer:layer] 来使用你的方法,所以我必须返回构造的子类实例本身:

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

和苹果warns在这种情况下反对使用 initWithLayer::

This initializer is used to create shadow copies of layers, for example, for the presentationLayer method. Using this method in any other situation will produce undefined behavior. For example, do not use this method to initialize a new layer with an existing layer’s content.

关于ios - CALayer 和 CATextLayer 之间的垂直对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46866737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com