ASTextNode的border与shadow属性不生效问题求助
我来帮你分析下这个问题的几个可能原因,结合Texture(原AsyncDisplayKit)的ASTextNode和ASTextBorder的工作机制来看:
1. BorderInsets设置不合理导致被裁剪或显示异常
你给ASTextBorder设置的insets包含负数:UIEdgeInsetsMake(10, -10, -1, -10),负数的内边距会让边框向文字内容的内部收缩(比如左右的-10会让边框往文字中心缩10pt,底部的-1会让边框向上缩1pt)。再加上你给textNode设置的textContainerInset = UIEdgeInsetsMake(0,10,5,10),两者叠加后,边框的左右部分很可能被文本容器的内边距裁剪,底部边框也会因为向上收缩变得几乎不可见。
建议先把border的insets调整为非负数,比如和textContainerInset对应的值:UIEdgeInsetsMake(10,10,5,10),再测试边框是否正常显示。
2. 阴影属性未正确配置
你提到shadow属性没生效,但当前代码里只创建了基础的ASTextBorder,完全没设置阴影相关的属性。要让阴影生效,必须显式配置shadowColor、shadowOffset、shadowRadius和shadowOpacity这几个参数,注意阴影颜色需要用CGColor类型,示例代码如下:
asBorder.shadowColor = UIColor.blackColor.CGColor; asBorder.shadowOffset = CGSizeMake(2, 2); asBorder.shadowRadius = 3; asBorder.shadowOpacity = 0.5;
3. 文本描边属性可能干扰视觉判断
你给文字设置了NSStrokeWidthAttributeName: @(-5)和NSStrokeColorAttributeName: UIColor.blackColor,这会给文字本身添加填充式的描边(负数width表示填充描边)。如果描边颜色和边框颜色对比不明显,很容易让你误以为边框没生效。可以先暂时注释掉这两个描边属性,单独测试边框的显示情况。
4. 确认Texture版本与渲染模式
某些旧版本的Texture对ASTextBorder的支持存在bug,建议确保你使用的是较新的版本。另外,ASTextNode默认是异步渲染模式,如果你修改过layerBacked属性,也可能影响边框渲染,可以尝试设置textNode.layerBacked = YES(默认是NO,不过异步模式下边框也应该正常生效,这可以作为排查手段)。
修正后的示例代码
CGFloat top = 10; CGFloat bottom = 5; UIEdgeInsets insets = UIEdgeInsetsMake(top, 10, bottom, 10); // 调整为非负数内边距 CGFloat radius = font.pointSize / 2; mps.alignment = textAlignment; ASTextNode *textNode = [ASTextNode new]; ASTextBorder *asBorder = [ASTextBorder borderWithFillColor:UIColor.redColor cornerRadius:radius]; asBorder.insets = insets; // 配置阴影属性 asBorder.shadowColor = UIColor.blackColor.CGColor; asBorder.shadowOffset = CGSizeMake(2, 2); asBorder.shadowRadius = 3; asBorder.shadowOpacity = 0.5; NSDictionary *attributes = @{ NSForegroundColorAttributeName: UIColor.whiteColor, NSFontAttributeName: font, // 先注释描边属性,测试边框正常后再根据需求添加 // NSStrokeWidthAttributeName: @(-5), // NSStrokeColorAttributeName: UIColor.blackColor, NSParagraphStyleAttributeName: mps, ASTextBorderAttributeName: asBorder, }; textNode.attributedText = [[NSAttributedString alloc] initWithString:text attributes:attributes]; textNode.textContainerInset = UIEdgeInsetsMake(0, 10, 5, 10); // 可选:尝试开启layerBacked排查问题 // textNode.layerBacked = YES; return textNode;
内容的提问来源于stack exchange,提问作者bolizhou

