简体   繁体   中英

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

I have a UIButton , on which I set a UIImage (by using set(_:for:) method). After that, I add a label on it with some text (It should be white). The problem is: When I use some photos, which have bright colours (close to white), it's hard to see some characters of the text. Here how it looks like (the button isn't very big, hence the quality of the image is low, too):

在此处输入图片说明

I've tried to add a UIView between the button and the label and to manipulate its alpha , but that doesn't help. If you know how the problem can be solved (without changing text's colour), I would appreciate your help.

The most common approach is to set the label's background color to a partially transparent black color. Then maybe round the labels corners for a nice look.

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

Another option, instead of adding a background to the label, is to use attribute text for the label and give the white text a black outline.

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

Yet another option is to setup the label with a shadow:

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

The shadow can be created using attribute text and this gives you more control:

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

This puts a halo around the text. Adjust the shadow properties to suit your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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