2015-12-18 29 views
2

我想學習Core Graphics,並且在使用drawRect時遇到此問題。 (圖片如下)黑框周圍drawRect形狀swift

我做了一個繼承自具有drawRect代碼的UIView的類。從我的viewcontroller類,我比設置尺寸和添加子視圖。

結果是在我的形狀周圍形成黑色框。我怎樣才能解決這個問題?

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() 

    } 
} 

enter image description here

回答

4

您需要設置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) 
0

您可以設置矩形的背景色

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