Search code examples
swiftswift4calayeruibezierpathcashapelayer

How to add zigzag border to circular image view


I have an image view I need to add a zigzag border to it like the image

Image wih zigzag border

How can I achieve this? Any Help is appreciated.

Thanks Chakshu Arora


Solution

  • Simple example using straight lines (curves are more complex, and I'd recommend creating a mask in a drawing program if that's what you need!).

    This code assumes a UIImageView in a storyboard...

    class DemoViewController: UIViewController {
    
        @IBOutlet weak var imageView: UIImageView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            setImageMask()
        }
    
        func setImageMask() {
    
            // Set the center and radius (pure circle rather than rectangle)
            let center = CGPoint(x: imageView.bounds.midX, y: imageView.bounds.midY)
            let radius = min(imageView.bounds.midX, imageView.bounds.midY)
    
            // Inset radius is the amount that the inner points are inset by
            let insetRadius: CGFloat = radius * 0.85
    
            // Calculate the segment arc sizes
            let numberOfPoints = 17
            let segmentArcSize = 360.0 / CGFloat(numberOfPoints)
            let arcMid = segmentArcSize / 2.0
    
            // Start at the top of the circle, but subtract half an arc so the outer point is at the top
            var angle = -90.0 - arcMid
    
            // Create the path
            let path = UIBezierPath()
    
            // Move to the inner starting point
            let startPoint = CGPoint(x: center.x + insetRadius * cos(angle.toRadians()) , y: center.y + insetRadius * sin(angle.toRadians()))
            path.move(to: startPoint)
    
            // Loop and draw the jagged points around the circlw
            for _ in 0 ..< numberOfPoints {
    
                // Outer point
                let midAngle = angle + arcMid
                let midPoint = CGPoint(x: center.x + radius * cos(midAngle.toRadians()), y: center.y + radius * sin(midAngle.toRadians()))
                path.addLine(to: midPoint)
    
                // Inner point
                let endAngle = angle + segmentArcSize
                let endPoint = CGPoint(x: center.x + insetRadius * cos(endAngle.toRadians()) , y: center.y + insetRadius * sin(endAngle.toRadians()))
                path.addLine(to: endPoint)
                angle += segmentArcSize
            }
    
            // End drawing
            path.close()
    
            // Mask the image view
            let mask = CAShapeLayer()
            mask.path = path.cgPath
            imageView.layer.mask = mask
        }
    
    }
    
    
    extension CGFloat {
    
        // Convert degrees to radians
    
        func toRadians() -> CGFloat {
            return self * CGFloat.pi / 180.0
        }
    }
    

    enter image description here