2017-04-06 162 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 
    } 

}