繁体   English   中英

如何使标签的文本在图像上方看起来不错?

[英]How to make a label's text look good on top of an image?

我有一个UIButton ,在上面设置了UIImage (通过使用set(_:for:)方法)。 之后,我在上面添加了一些文本标签(应该是白色)。 问题是:当我使用一些颜色鲜艳(接近白色)的照片时,很难看到文本的某些字符。 这是它的外观(按钮不是很大,因此图像的质量也很低):

在此处输入图片说明

我试图在按钮和标签之间添加UIView并操纵其alpha ,但这无济于事。 如果您知道该问题的解决方法(无需更改文本的颜色),请多多帮助。

最常见的方法是将标签的背景色设置为部分透明的黑色。 然后,可以将标签的角弄圆一些,以获得漂亮的外观。

let label = ... // your label 
label.backgroundColor = UIColor(white: 0.0, alpha: 0.4) // adjust alpha as desired
label.layer.cornerRadius = 4 // adjust as desired

替代向标签添加背景的另一种方法是对标签使用属性文本,并为白色文本提供黑色轮廓。

let attrs: [NSAttributedStringKey: Any] = [
    .foregroundColor: UIColor.white,
    .strokeColor: UIColor.black,
    .strokeWidth: -2.0,
    .font: UIFont.systemFont(ofSize: 20) // Use whatever font you want
]
let attrStr = NSAttributedString(string: "Grand Royal", attributes: attrs)
label.attributedText = attrStr

另一个选择是使用阴影设置标签:

let label = ... // your label 
label.shadowColor = .black
label.shadowSize = CGSize(width: 1, height: 1)

可以使用属性文本创建阴影,这可以为您提供更多控制:

let shadow = NSShadow()
shadow.shadowColor = UIColor.black
shadow.shadowOffset = CGSize(width: 0, height: 0)
shadow.shadowBlurRadius = 3
let attrs: [NSAttributedStringKey: Any] = [
    .foregroundColor: UIColor.white,
    .shadow: shadow,
    .font: UIFont.systemFont(ofSize: 40)
]
let attrStr = NSAttributedString(string: "Grand Royal", attributes: attrs)
label.attributedText = attrStr

这给文本加上了光环。 调整阴影属性以适合您的需求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM