Search code examples
iosswiftcore-graphics

Draw a round edge parallelogram with some shadow offset


I am trying to draw a parallelogram with round edges. I want it to be configurable so that I can one of the vertical edge at 90 degree.

As you can see in the image that topLeft corner is not rounded with code below

func getParallelogram(width: CGFloat, height: CGFloat, radius: CGFloat) -> CGPath {
        // Points of the parallelogram
        var points = [
            CGPoint(x: width * 0.05, y: 0),
            CGPoint(x: width , y: 0),
            CGPoint(x: width - width * 0.05, y: height),
            CGPoint(x: 0, y: height)
        ]

        let point1 = points[0]
        let point2 = points[1]
        let point3 = points[2]
        let point4 = points[3]

        let path = CGMutablePath()

        path.move(to: point1)
        path.addArc(tangent1End: point1, tangent2End: point2, radius: radius)
        path.addArc(tangent1End: point2, tangent2End: point3, radius: radius)
        path.addArc(tangent1End: point3, tangent2End: point4, radius: radius)
        path.addArc(tangent1End: point4, tangent2End: point1, radius: radius)
        return path
    }

Usage:

let customView = UIView(frame: CGRect(x: 20, y: 50, width: 320, height: 300))
customView.backgroundColor = UIColor.clear
view.addSubview(customView)

let shape = CAShapeLayer()
shape = UIColor.lightGray.cgColor
shape.path = getParallelogram(width: 200, height: 80, radius: 5)
shape.position = CGPoint(x: 10, y: 10)
shape.layer.addSublayer(triangle)

The problem i am facing here is that the top left corner is not round when with above code. I would appreciate any help to achieve this. Also please guide me if there is any other alternative or simpler approach. Thanks!

Note: I am using this code to covert Triangle to Parallelogram UIBezierPath Triangle with rounded edges


Solution

  • Change

        path.move(to: point1)
        path.addArc(tangent1End: point1, tangent2End: point2, radius: radius)
        path.addArc(tangent1End: point2, tangent2End: point3, radius: radius)
        path.addArc(tangent1End: point3, tangent2End: point4, radius: radius)
        path.addArc(tangent1End: point4, tangent2End: point1, radius: radius)
    

    to

        path.move(to: point1)
        path.addArc(tangent1End: point2, tangent2End: point3, radius: radius)
        path.addArc(tangent1End: point3, tangent2End: point4, radius: radius)
        path.addArc(tangent1End: point4, tangent2End: point1, radius: radius)
        path.addArc(tangent1End: point1, tangent2End: point2, radius: radius)
    

    Result:

    enter image description here