【问题标题】:Cant Change UIView Background Color From Black无法从黑色更改 UIView 背景颜色
【发布时间】:2017-05-30 16:36:06
【问题描述】:

这是我第一次遇到 drawRect 的问题。我有一个简单的 UIView 子类,其中包含要填充的路径。一切顺利。路径被正确填充,但无论如何背景仍然是黑色。我该怎么办?我的代码如下:

var color: UIColor = UIColor.red {didSet{setNeedsDisplay()}}

private var spaceshipBezierPath: UIBezierPath{
    let path = UIBezierPath()
    let roomFromTop: CGFloat = 10
    let roomFromCenter: CGFloat = 7
    path.move(to: CGPoint(x: bounds.minX, y: bounds.maxY))
    path.addLine(to: CGPoint(x: bounds.minX, y: bounds.minY+roomFromTop))
    path.addLine(to: CGPoint(x: bounds.midX-roomFromCenter, y: bounds.minY+roomFromTop))
    path.addLine(to: CGPoint(x: bounds.midX-roomFromCenter, y: bounds.minY))
    path.addLine(to: CGPoint(x: bounds.midX+roomFromCenter, y: bounds.minY))
    path.addLine(to: CGPoint(x: bounds.midX+roomFromCenter, y: bounds.minY+roomFromTop))
    path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY+roomFromTop))
    path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY))
    path.addLine(to: CGPoint(x: bounds.minX, y: bounds.maxY))
    return path
}

override func draw(_ rect: CGRect) {
    color.setFill()
    spaceshipBezierPath.fill()
}

视图如下所示:

【问题讨论】:

  • 我不确定,但可能在 spaceshipBezierPath 的返回路径之前添加 path.close()
  • 不。试过了,但没有用。感谢您的帮助
  • @Nikhi Sridhar,我使用你的代码来绘制矩形,但得到颜色,在我看来你的红色是蓝色,你的黑色是白色。你想得到什么效果?

标签: ios swift uiview colors draw


【解决方案1】:

我有一个简单的 UIView 子类...但无论如何背景仍然是黑色

这种情况通常是因为您忘记将 UIView 子类的 isOpaque 设置为 false在 UIView 子类的初始化程序中这样做是个好主意,这样它就足够早了。

例如,在这里我对您的代码进行了非常轻微的调整。这是我正在使用的完整代码:

class MyView : UIView {
    private var spaceshipBezierPath: UIBezierPath{
        let path = UIBezierPath()
        // ... identical to your code
        return path
    }
    override func draw(_ rect: CGRect) {
        UIColor.red.setFill()
        spaceshipBezierPath.fill()
    }
}

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()        
        let v = MyView(frame:CGRect(x: 100, y: 100, width: 200, height: 200))
        self.view.addSubview(v)
    }
}

注意黑色背景:

现在我将这些行添加到 MyView:

override init(frame:CGRect) {
    super.init(frame:frame)
    self.isOpaque = false
}
required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

看到不同之处了吗?

【讨论】:

  • willMove(toSuperview) 中设置isOpaque 是否是一个有效的替代方案?例如?
  • @andreas1724 当然,我想是的——如果你的情况需要的话。那也应该“足够早”。
【解决方案2】:

在我的情况下,我解决的是从背景颜色“无颜色”切换到背景颜色“透明颜色”

【讨论】:

    【解决方案3】:

    对于未来的寻求者......

    我遇到了同样的问题,但 @matt 解决方案对我不起作用。

    在我的场景中,我在另一个 UIView (B) 后面有一个 UIView (A)。 UIView (A) 具有背景色,而 UIView (B) 是透明的。值得注意的是,B 被子类化以使用 UIBezier 通过覆盖 draw 方法创建自定义形状。

    原来在这种情况下,透明的 UIView 没有任何意义,我必须为 B 设置相同的背景颜色,或者删除 A 的背景颜色。

    没有其他办法,所以如果你有同样的情况,不要浪费你的时间!

    【讨论】:

      猜你喜欢
      • 2014-09-25
      • 1970-01-01
      • 2013-02-22
      • 1970-01-01
      • 2020-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多