2017-04-06 163 views
0

我想繪製一個連接矩形兩個角的透明圓弧,以便通過圓弧可以看到背後的視圖。繪製透明圓弧

我可以能夠使用下面的代碼

override func draw(_ rect: CGRect) { 
    // Drawing code 
    let arcHeight: CGFloat = 10 
    let arcColor = UIColor.blue 
    let arcRect = CGRect(x: 0, y: rect.height - arcHeight, width: rect.width, height: arcHeight) 
    let arcRadius = (arcHeight/2) + (pow(arcRect.width, 2)/(8 * arcHeight)) 
    let arcCenter = CGPoint(x: arcRect.origin.x + (arcRect.width/2), y: arcRect.origin.y + arcRadius) 

    let angle = acos(arcRect.width/(2 * arcRadius)) 
    let startAngle = radians(180) + angle 
    let endAngle = radians(360) - angle 

    let path = UIBezierPath(arcCenter: arcCenter, radius: arcRadius/2, startAngle: startAngle, endAngle: endAngle, clockwise: true) 
    path.lineWidth = arcRadius 
    arcColor.setStroke() 
    path.stroke() 
} 

private func radians(_ degrees: CGFloat) -> CGFloat { 
    return degrees * CGFloat(M_PI)/180 
} 

所以使電弧透明我需要填寫不包括弧形的,該矩形的其餘部分我想下面的代碼,以畫圓弧,

let fullPath = UIBezierPath(rect: bounds) 
fullPath.append(path) 
fullPath.usesEvenOddFillRule = true 
fullPath.addClip() 
arcColor.setFill() 
fullPath.fill() 

但我不能達到我的預期。請指導我如何填充矩形,不包括弧線。

請從下面的截圖中,

I want the white arc to be transparent

我想要的白色弧線上面的圖片中是透明的,這樣我可以看到什麼是通過弧的觀點後面。

回答

2

看樣子你想是這樣的:

enter image description here

要獲取的是,我用幾乎相同的代碼,但我先用藍色充滿了整個rect,然後我畫的弧線,使用你的代碼,但是當我們開始衝擊弧線時,我們用.clear的混合模式衝擊它,因此會清除弧線以下的區域。

class MyView : UIView { 
    override init(frame:CGRect) { 
     super.init(frame:frame) 
     self.isOpaque = false 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

    override func draw(_ rect: CGRect) { 
     // Drawing code 
     let arcHeight: CGFloat = 10 
     let arcColor = UIColor.blue 
     arcColor.setFill() // <-- 
     let con = UIGraphicsGetCurrentContext() // <-- 
     con?.fill(rect) // <-- 
     let arcRect = CGRect(x: 0, y: rect.height - arcHeight, width: rect.width, height: arcHeight) 
     // ... same as your code ... 
     path.stroke(with: .clear, alpha: 1) 
    } 

    private func radians(_ degrees: CGFloat) -> CGFloat { 
     return degrees * CGFloat(M_PI)/180 
    } 

}