要制作圆形视图,必须这样做
shapeView.layer.cornerRadius = CGFloat(width)/2.0
所以我将这个逻辑扩展为椭圆形视图
if width >= height { shapeView.layer.cornerRadius = CGFloat(width)/2.0 } else{ shapeView.layer.cornerRadius = CGFloat(height)/2.0 }
除了我的椭圆形视图有尖端,你可以在这里看到.
我的问题是:我如何摆脱尖端并使它们成为圆形?
如果我正在使用它的任何问题:
斯威夫特2
IOS 9.2
Xcode 7.2
rob mayoff.. 8
使用a 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
结果:
使用a 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
结果: