使用CAShapeLayer
爲您的圖層蒙版:
class OvalView: UIView {
override func layoutSubviews() {
super.layoutSubviews()
layoutOvalMask()
}
private func layoutOvalMask() {
let mask = self.shapeMaskLayer()
let bounds = self.bounds
if mask.frame != bounds {
mask.frame = bounds
mask.path = CGPathCreateWithEllipseInRect(bounds, nil)
}
}
private func shapeMaskLayer() -> CAShapeLayer {
if let layer = self.layer.mask as? CAShapeLayer {
return layer
}
let layer = CAShapeLayer()
layer.fillColor = UIColor.blackColor().CGColor
self.layer.mask = layer
return layer
}
}
演示:
let backgroundView = UIView(frame: CGRectMake(0, 0, 450, 250))
backgroundView.backgroundColor = UIColor.redColor()
let ovalView = OvalView(frame: CGRectMake(25, 25, 400, 200))
backgroundView.addSubview(ovalView)
let imageView = UIImageView(image: UIImage(named: "image.jpg"))
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.frame = ovalView.bounds
ovalView.addSubview(imageView)
XCPlaygroundPage.currentPage.liveView = backgroundView
結果:
![oval mask](https://i.stack.imgur.com/hQPna.png)
您不能創建使用'cornerRadius'的橢圓。 – rmaddy