How to Crop the UIView with repeated semi circle?

Deadly 提交于 2019-12-19 04:44:30

问题


I want to crop an UIView with bottom and top of repeated semi circle like this image


回答1:


I had been working on your question and here is my results, you need create a UIBezierPath and apply to your desired view, use this code for that

Function to generate the desired BezierPath

func pathSemiCirclesPathForView(givenView: UIView, ciclesRadius:CGFloat = 10, circlesDistance : CGFloat = 2) ->UIBezierPath
    {
        let width = givenView.frame.size.width
        let height = givenView.frame.size.height

        let semiCircleWidth = CGFloat(ciclesRadius*2)

        let semiCirclesPath = UIBezierPath()
        semiCirclesPath.move(to: CGPoint(x:0, y:0))

        var x = CGFloat(0)
        var i = 0
        while x < width {
            x = (semiCircleWidth) * CGFloat(i) + (circlesDistance * CGFloat(i))
            let pivotPoint = CGPoint(x: x + semiCircleWidth/2, y: height)
            semiCirclesPath.addArc(withCenter: pivotPoint, radius: ciclesRadius, startAngle: -180 * .pi / 180.0, endAngle: 0 * .pi / 180.0, clockwise: true)
            semiCirclesPath.addLine(to: CGPoint(x: semiCirclesPath.currentPoint.x + circlesDistance, y: height))
            i += 1
        }

        semiCirclesPath.addLine(to: CGPoint(x:width,y: 0))

        i = 0
        while x > 0 {
            x = width - (semiCircleWidth) * CGFloat(i) - (circlesDistance * CGFloat(i))
            let pivotPoint = CGPoint(x: x - semiCircleWidth/2, y: 0)
            semiCirclesPath.addArc(withCenter: pivotPoint, radius: ciclesRadius, startAngle: 0 * .pi / 180.0, endAngle: -180 * .pi / 180.0, clockwise: true)
            semiCirclesPath.addLine(to: CGPoint(x: semiCirclesPath.currentPoint.x - circlesDistance, y: 0))
            i += 1
        }

        semiCirclesPath.close()
        return semiCirclesPath
    }

Function to apply the BezierPath to any View

func applySemiCircleEffect(givenView: UIView){
    let shapeLayer = CAShapeLayer(layer: givenView.layer)
    shapeLayer.path = self.pathSemiCirclesPathForView(givenView: givenView).cgPath
    shapeLayer.frame = givenView.bounds
    shapeLayer.masksToBounds = true
    shapeLayer.shadowOpacity = 1
    shapeLayer.shadowColor = UIColor.black.cgColor
    shapeLayer.shadowOffset = CGSize(width: 0, height: 0)
    shapeLayer.shadowRadius = 3

    givenView.layer.mask = shapeLayer
}

Use it

@IBOutlet weak var customView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    self.applySemiCircleEffect(givenView: customView)
}

This is how it looks

Hope this helps you, Happy Coding



来源:https://stackoverflow.com/questions/45115304/how-to-crop-the-uiview-with-repeated-semi-circle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!