【问题标题】:Why is the background color of my drawable view black?为什么我的可绘制视图的背景颜色是黑色的?
【发布时间】:2016-07-22 11:37:45
【问题描述】:

我希望我的UIViewbackgroundColor 属性为红色或黄色。但是,视图显示为黑色。

class RenderView:UIView {

    var pointsToDraw:[Int] = [] {
        didSet {
            self.setNeedsDisplay()
        }
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        self.backgroundColor = UIColor.whiteColor()
    }


    override func drawRect(rect: CGRect) {

        let context = UIGraphicsGetCurrentContext();
        CGContextClearRect(context, self.bounds);
        CGContextSetLineWidth(context, 3);
        UIColor.yellowColor().set()


        if pointsToDraw.count > 4 {

            CGContextMoveToPoint(context, CGFloat(pointsToDraw[0]), CGFloat(pointsToDraw[1]))

            for i in 2..<pointsToDraw.count {
                if i % 2 == 0 {
                    CGContextAddLineToPoint(context, CGFloat(pointsToDraw[i]), CGFloat(pointsToDraw[i + 1]))
                }
            }
        }

        // Draw
        CGContextStrokePath(context);
    }
}

我可以在视图上绘制的线是黄色的,但视图仍然是黑色的。 Here's a sample project。您认为为什么会发生这种情况?

【问题讨论】:

  • 您是否有理由需要致电CGContextClearRect?它正在清除背景颜色 - 然后你永远不会重新绘制自己的背景。因此结果将是黑色的。

标签: ios swift uiview background-color


【解决方案1】:

这是因为你打电话给CGContextClearRect。这个调用的效果可能非常棘手(正如我解释的in my online book)。如果您希望视图的背景为红色,那么在 drawRect: 的开头您应该用红色填充上下文的边界。

【讨论】:

    猜你喜欢
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多