基于路径的掩码,具有良好的抗锯齿function

我想用一个圆圈掩盖一个正方形。 我正在使用它而不是角半径,因为我以后想做动画。

我可以让它掩盖,但边缘非常粗糙:

在此处输入图像描述

// Target View let targetView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) targetView.backgroundColor = UIColor.redColor() // Mask let maskingPath = UIBezierPath() let half = targetView.frame.width / 2 maskingPath.addArcWithCenter(CGPoint(x: half, y: half), radius: half, startAngle: 0, endAngle: 360, clockwise: true) let maskingLayer = CAShapeLayer() maskingLayer.path = maskingPath.CGPath // Maybe setting contentsScale? // maskingLayer.contentsScale = UIScreen.mainScreen().scale // doesn't change anything, sorry // Maybe enabling edgeAntialiasing? // maskingLayer.allowsEdgeAntialiasing = true // also doesn't change anything // Magnification filter? // maskingLayer.magnificationFilter = kCAFilterNearest // nuttin' targetView.layer.mask = maskingLayer 

我尝试过zoomFilter和其他一些东西。

如何添加抗锯齿的可动画圆形遮罩?

你给addArcWithCenter一个角度度:

 maskingPath.addArcWithCenter(CGPoint(x: half, y: half), radius: half, startAngle: 0, endAngle: 360, clockwise: true) 

但是文档说明角度应该是弧度。

因此,您需要多次创建一个与自身重叠的路径。 边缘在先前的边缘通道的顶部绘制,在同一位置。 在足够的传球建立后,他们最终看起来不透明(或几乎如此)。 如果您在彼此之上创建多个圆形路径,您会看到类似的东西。

这对我来说效果更好:

 maskingPath.addArcWithCenter(CGPoint(x: half, y: half), radius: half, startAngle: 0, endAngle: CGFloat(M_PI * 2.0), clockwise: true) 

(但是因为你真的想要一个封闭的椭圆形,你应该像你在答案中那样使用UIBezierPath(ovalInRect: targetView.bounds) 。)

找到了解决方案,但不是根本原因。

这将绘制脆皮:

 let maskingPath = UIBezierPath() let half = targetView.frame.width / 2 maskingPath.addArcWithCenter(CGPoint(x: half, y: half), radius: half, startAngle: 0, endAngle: 360, clockwise: true) let maskingLayer = CAShapeLayer() maskingLayer.path = maskingPath.CGPath targetView.layer.mask = maskingLayer 

这将绘制好的和抗锯齿:

 let maskingLayer = CAShapeLayer() maskingLayer.path = UIBezierPath(ovalInRect: targetView.bounds).CGPath targetView.layer.mask = maskingLayer 

希望我知道为什么。 它们都是用作图层蒙版的CGPath

编辑:库尔特指出,我正在绘制360弧度,就像一遍又一遍地绘制同一个圆圈,看起来不透明,破坏正在发生的任何抗锯齿。