当前位置:  开发笔记 > IOS > 正文

如何创建椭圆形UIView?

如何解决《如何创建椭圆形UIView?》经验,为你挑选了1个好方法。

要制作圆形视图,必须这样做

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

结果:

椭圆形面具



1> rob mayoff..:

使用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

结果:

椭圆形面具

推荐阅读
贾志军
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有