如何使用重复的半圆来裁剪UIView? [英] How to Crop the UIView with repeated semi circle?

查看:96
本文介绍了如何使用重复的半圆来裁剪UIView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用重复的半圆的底部和顶部来裁剪UIView,如该图像

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

推荐答案

我一直在研究您的问题,这是我的结果,您需要创建一个UIBezierPath并将其应用于所需的视图,为此使用此代码

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

用于生成所需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
    }

将BezierPath应用于任何视图的功能

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
}

使用

@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)
}

这是它的样子

希望这对您有帮助,快乐编码

Hope this helps you, Happy Coding

这篇关于如何使用重复的半圆来裁剪UIView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆