Dmitry Klochkov
Dmitry Klochkov

Reputation: 2635

Why setting isOpaque to true on CATextLayer makes the background black?

I am trying to reduce number of blended layers in order to improve performance. I use CATextLayer to display some labels. I set the text color with the foregroundColor property and the background color through backgroundColor.

The problem is when I set isOpaque to true the background color of the layer becomes black no matter what the backgroundProperty is.

Can someone explain what is happening here and how can I keep my background color while setting isOpaque to true?

Here is swift playground code to reproduce the issue:

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        let label = CATextLayer()
        label.frame = CGRect(x: 150, y: 200, width: 200, height: 50)
        label.string = "My label"
        label.foregroundColor = UIColor.gray.cgColor
        label.backgroundColor = UIColor.orange.cgColor
        label.isOpaque = true

        view.layer.addSublayer(label)
        self.view = view
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

And the result (I expect the background of the textLayer to be orange but it is black as you can see):

enter image description here

Upvotes: 1

Views: 320

Answers (1)

Bartosz Ciechanowski
Bartosz Ciechanowski

Reputation: 10333

The comment in the header is clear:

/* A hint marking that the layer contents provided by -drawInContext:
 * is completely opaque. Defaults to NO. Note that this does not affect
 * the interpretation of the `contents' property directly. */

By setting isOpaque to true you're telling Core Animation that the contents is opaque and doesn't need an alpha channel. Simply don't set that property to true.

Upvotes: 2

Related Questions