drawRect 形状周围的黑框 swift

black box around drawRect shape swift

我正在尝试学习 Core Graphics,但在使用 drawRect 时遇到了这个问题。 (下图)

我做了一个 class 继承自具有 drawRect 代码的 UIView。在我的 viewcontroller class 中,我设置了尺寸并添加了子视图。

结果是我的形状周围有一个黑框。我该如何解决这个问题?

class myViewController: UIViewController {

var bg = Background()

override func viewDidLoad() {
    super.viewDidLoad()

    bg = Background(frame: CGRectMake(50, 50, 50, 50))
    self.view.addSubview(bg)
    self.view.sendSubviewToBack(bg)
}


class Background: UIView {

override func drawRect(rect: CGRect) {
    // Drawing code

    var path = UIBezierPath(ovalInRect: rect)
    UIColor.greenColor().setFill()
    path.fill()

  }
}

您需要设置 bg 元素的背景颜色,只需添加这一行 bg.backgroundColor = UIColor.clearColor()。因此,在您的 viewDidLoad 方法中,将代码更新为:

bg = Background(frame: CGRectMake(50, 50, 50, 50))
bg.backgroundColor = UIColor.clearColor()
self.view.addSubview(bg)
self.view.sendSubviewToBack(bg)

可以设置矩形的背景颜色

class Background: UIView {
  override func drawRect(rect: CGRect) {
    UIColor.whiteColor().setFill()
    UIRectFill(rect)
    let path = UIBezierPath(ovalInRect: rect)
    UIColor.greenColor().setFill()
    path.fill()
  }
}