2017-01-15 111 views
4

這是我第一次遇到與drawRect有關的問題。我有一個簡單的UIView子類和一個要填充的路徑。一切安好。路徑得到正確填充,但無論如何,背景仍然是黑色的。我該怎麼辦?我的代碼如下:無法更改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() 
} 

這裏是視圖的樣子: enter image description here

+0

我不知道,但也許()'在spaceshipBezierPath – Grifas

+0

都能跟得上返回路徑之前添加'path.close。試過,但沒有奏效。謝謝你的幫助,雖然 –

+0

@Nikhi Sridhar,我用你的代碼繪製矩形但是獲得顏色,在我看來你的紅色是藍色的,你的黑色是白色的。你想得到什麼效果? – aircraft

回答

6

我有一個簡單的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) 
    } 
} 

通知黑色背景:

enter image description here

現在我將這些行添加到MyView的:

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

見差讓?

enter image description here

+0

非常感謝。它完美的作品。 –