首页 > 解决方案 > 如何从 UILabel 文本创建 CGPathRef?

问题描述

我将为 UILabel 制作一个阴影路径,它概述了它的文本。UILabel 文本是否可以以某种方式转换为 CGPath?

标签: iosobjective-c

解决方案


我建议最简单的方法是设置图层的阴影属性。

在 Objective-C 中:

self.label.layer.shadowColor = UIColor.blackColor.CGColor;
self.label.layer.shadowRadius = 10;
self.label.layer.shadowOpacity = 1;
self.label.layer.shadowOffset = CGSizeZero;

在斯威夫特:

label.layer.shadowColor = UIColor.black.cgColor
label.layer.shadowRadius = 10
label.layer.shadowOpacity = 1
label.layer.shadowOffset = .zero

产量:

在此处输入图像描述

你说:

但是,在图层中我有一些额外的内容,我不想添加阴影。

如果您有干扰阴影的子视图或子图层,我建议您将该内容移出标签并进入它们自己的视图层次结构。如果不知道您添加到标签中的子图层/子视图,很难具体说明。


你说:

...我也需要阴影的不透明度,没有图层是不可能的。

这并不完全正确。您可以使用该NSAttributedString模式并将 alpha 指定为shadowColor.

例如在 Objective-C 中:

NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowOffset = CGSizeZero;
shadow.shadowBlurRadius = 20;
shadow.shadowColor = [UIColor.blackColor colorWithAlphaComponent:1];

NSDictionary<NSAttributedStringKey, id> *attributes = @{ NSShadowAttributeName: shadow };

NSMutableAttributedString *string = [self.label.attributedText mutableCopy];
[string setAttributes:attributes range:NSMakeRange(0, string.length)];

self.label.attributedText = string;

或者在 Swift 中:

let shadow = NSShadow()
shadow.shadowOffset = .zero
shadow.shadowBlurRadius = 20
shadow.shadowColor = UIColor.black.withAlphaComponent(1)

let attributes: [NSAttributedString.Key: Any] = [.shadow: shadow]

guard let string = label.attributedText?.mutableCopy() as? NSMutableAttributedString else { return }
string.setAttributes(attributes, range: NSRange(location: 0, length: string.length))
label.attributedText = string

推荐阅读