这是我第一次遇到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() }
以下是视图的样子:
我有一个简单的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") }
看看有什么区别?