【问题标题】:Why setting isOpaque to true on CATextLayer makes the background black?为什么在 CATextLayer 上将 isOpaque 设置为 true 会使背景变黑?
【发布时间】:2019-05-27 13:46:05
【问题描述】:

我正在尝试减少混合层的数量以提高性能。我使用 CATextLayer 来显示一些标签。我使用foregroundColor 属性设置文本颜色,通过backgroundColor 设置背景颜色。

问题是当我将isOpaque 设置为true 时,无论backgroundProperty 是什么,图层的背景颜色都会变为黑色。

有人能解释一下这里发生了什么吗?如何在将isOpaque 设置为true 时保持背景颜色?

这里是重现问题的快速操场代码:

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()

结果(我希望 textLayer 的背景是橙色的,但你可以看到它是黑色的):

【问题讨论】:

  • 改用UILabel
  • 是的,我知道 UILabel 没有这个问题,但仍然很高兴知道 CATextLayer 发生了什么

标签: ios core-animation calayer


【解决方案1】:

表头注释清楚:

/* 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. */

通过将isOpaque 设置为true,您是在告诉Core Animation 内容是不透明的并且不需要Alpha 通道。只是不要将该属性设置为true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    相关资源
    最近更新 更多