ios - 如何从 UILabel 文本创建 CGPathRef?
问题描述
我将为 UILabel 制作一个阴影路径,它概述了它的文本。UILabel 文本是否可以以某种方式转换为 CGPath?
解决方案
我建议最简单的方法是设置图层的阴影属性。
在 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
推荐阅读
- java - JPA-如何避免使用合并将子实体更新为默认值
- javascript - 如何在 div 中显示文本编辑器并在单击按钮后显示添加的内容?
- angular - 在 Asp.net core 2 Visual Studio 2017 上使用 --environments 和 Angular SPA
- hadoop - logstash 非法状态异常?
- javascript - 使用javascript将逗号分隔的数组减少为字符串
- xml - 如何使用 powershell 将数据插入 XML 子元素
- nativescript - 相机拍摄功能不适用于 ios
- java - 触摸播放音频 - Android
- laravel-5 - 不带域名的 Apache 配置文件名
- 32-bit - Rakudo x86 32 位预编译安装程序/二进制文件在哪里?