Search code examples
ioscore-graphicscore-animation

Drawing grid using CAShapeLayer


Long story short I want draw a diagonal grid on CALayerShape. My code instead of straight lines produces some kind of curved craziness. It looks very interesting and I wish it would be desired effect, but no, it's not.

My questions: 1. How can I draw straight lines using CAShapeLayer? 2. Did I discover some kind of black hole that affects gravity of pixels in my simulator?

func drawPath(_view:UIView, phase:CGFloat, segment:CGFloat){
        // we need two runs
        var height = CGRectGetHeight(view.frame)
        let width = CGRectGetWidth(view.frame)

        let segment:CGFloat = 40
        var currentX:CGFloat = segment
        var cgpath =  CGPathCreateMutable()

        for var y = height; y > 0 ; y = y - segment {


            CGPathMoveToPoint(cgpath, nil, 0, y)
            CGPathAddLineToPoint(cgpath, nil, currentX, 0)
            CGPathCloseSubpath(cgpath)

            currentX += segment
        }

        var layer = CAShapeLayer()
        layer.path = cgpath
        layer.strokeColor = UIColor.redColor().CGColor
        layer.lineWidth = 1
        layer.fillColor = UIColor.blackColor().CGColor

        view.layer.addSublayer(layer)


    }

distorted grid


Solution

  • What you've drawn is actually straight lines. The fact that it looks curved is an optical illusion. You can get this same effect with yarn and a piece of cardboard.

    Your code is doing the wrong thing.

    You need to map out the diagonal grid you want with graph paper, figure out the endpoints of your diagonal grid, and then come up with a loop that gives you those endpoints.

    If you want to draw a diagonal grid in a 5x5 rectangle you'd draw lines like this:

    0,1 to 1,0
    0,2 to 2,0
    0,3 to 3,0
    0,4 to 4,0
    

    Your grid spacing is probably more like 20 or 30 points than every point, and your whole grid is probably the full size of the screen, but you get the idea.