Swift 2 中的 UIImageView 饼图蒙版

UIImageView Pie Mask in Swift 2

Swift 中搜索了有关如何屏蔽图像的大量资源后,我发现许多资源使用 UIImage 而不是 UIImageView。它变得非常混乱,因为它们几乎相似,但它们不共享一些相同的子类和属性。

我有一张图像将被添加到堆栈视图中,尽管我希望用具有固定开始和结束角度的圆形遮盖此图像。

例子:

原始图片和所需蒙版结果

我想强调一下,我正在模拟一个被切掉的馅饼,所以基本上我是在用馅饼的大小裁剪图像。

这是我迄今为止尝试开始的(但我一直失败)...

let testPicture:UIImageView = UIImageView(image: UIImage(named: "myPicture"))
testPicture.contentMode = .ScaleAspectFit
testPicture.layer.borderWidth = 1
testPicture.clipsToBounds = true
testPicture.layer.masksToBounds = true
view.layer.addSublayer(shapeLayer)

// ???
// UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: clockwise).CGPath

self.myStackView.addArrangedSubview(testPicture)
self.myStackView.layoutIfNeeded()

当其他来源仅使用 UIImage 时,我无法弄清楚如何应用具有几何函数的掩蔽图像的相同实现。

生成饼图蒙版的新代码(尝试)

let center = CGPointMake(testPicture.frame.size.width / 2, testPicture.frame.size.height / 2)
let radius = CGFloat((CGFloat(testPicture.frame.size.width) - CGFloat(1.0)) / 2)
let midX = (testPicture.layer.frame.width-testPicture.layer.frame.width)/2
let midY = (testPicture.layer.frame.height-testPicture.layer.frame.height)/2

let circlePath = UIBezierPath(arcCenter: CGPoint(x: midX , y: midY), radius: radius, startAngle: CGFloat(10), endAngle:CGFloat(M_PI * 2), clockwise: true)

let maskLayer = CAShapeLayer()
maskLayer.path = circlePath.CGPath

testPicture.layer.mask = maskLayer
testPicture.clipsToBounds = true
testPicture.layer.masksToBounds = true

要遮罩图层,请将单独的图层分配给 mask 属性。在这种情况下,我认为您正在寻找的是:

testPicture.layer.mask = shapeLayer