hackintosh
hackintosh

Reputation: 21

CAShapeLayer shape not displaying

My CAShapeLayer is not being displayed. I'm trying to create a shape by looping through an array of CGPoints. I need to use either an array or dictionary so I can later add different sets of CGPoints to create more complex shapes.

var shapeLayer = CAShapeLayer()
var color = UIColor.redColor()
var openPath = UIBezierPath()
var closedPath = UIBezierPath()
let points = [CGPoint(x: 30, y: 30), CGPoint(x: 90, y: 30), CGPoint(x: 90, y: 90), CGPoint(x: 90, y: 30), CGPoint(x: 30, y: 30)]
var firstTime = false

override func viewDidLoad()
{
    super.viewDidLoad()
    setOpenPath()
}

func setOpenPath()
{
    for number in points
    {
        if number != points.first
        {
           openPath.addLineToPoint(number)
        }

        if number == points.first
        {
            if firstTime == false
            {
                openPath.moveToPoint(number)
            }
            if firstTime == true
            {
                openPath.addLineToPoint(number)
                setClosePath()
            }
            firstTime = true
        }
    }
}

func setClosePath()
{
    firstTime = false
    closedPath.CGPath = CGPathCreateMutableCopy(openPath.CGPath)
    closedPath.closePath()
    setShapeLayer()
}

func setShapeLayer()
{
    shapeLayer.path = closedPath.CGPath
    shapeLayer.fillColor = UIColor.greenColor().CGColor
    shapeLayer.fillRule = kCAFillRuleNonZero
    self.view.layer.addSublayer(shapeLayer)
}

If i replace the code inside setOpenPath() with the code below, the script works fine.

openPath.moveToPoint(CGPoint(x: 30, y: 30))
openPath.addLineToPoint(CGPoint(x: 90, y: 30))
openPath.addLineToPoint(CGPoint(x: 90, y: 90))
openPath.addLineToPoint(CGPoint(x: 30, y: 90))
openPath.addLineToPoint(CGPoint(x: 30, y: 30))
setClosePath()

Upvotes: 2

Views: 481

Answers (1)

rakeshbs
rakeshbs

Reputation: 24572

Your points are messed up in the points array. element at index 3 is wrong when compared to your code below. It does not produce a closed path. The correct elements are

let points = [CGPoint(x: 30, y: 30), CGPoint(x: 90, y: 30), CGPoint(x: 90, y: 90), CGPoint(x: 30, y: 90), CGPoint(x: 30, y: 30)]

Also use else conditions and simplify your loop like this

func setOpenPath()
{
    firstTime = true
    for number in points
    {
        if number != points.first
        {
            openPath.addLineToPoint(number)
        }
        else
        {
            if firstTime
            {
                openPath.moveToPoint(number)
            }
            else
            {
                openPath.addLineToPoint(number)
                setClosePath()
            }
            firstTime = false
        }
    }
}

Upvotes: 1

Related Questions