Swift: Playground Hack of the day

Today’s hack creates a random Bezier Path.  You pass a size, it builds a shape, using all three path types (line, quad curve, cubic curve). I wrote this for testing path routines and image rendering, but it’s fun to simply sit there and re-run the playground over and over.

func RandomShape(size : CGSize) -> UIBezierPath {
    func RandomFloat() -> CGFloat {return CGFloat(arc4random()) / CGFloat(UINT32_MAX)}
    func RandomPoint() -> CGPoint {return CGPointMake(size.width * RandomFloat(), size.height * RandomFloat())}
    let path = UIBezierPath(); path.moveToPoint(RandomPoint())
    for _ in 0..<(3 + Int(arc4random_uniform(numericCast(10)))) {
        switch (random() % 3) {
        case 0: path.addLineToPoint(RandomPoint())
        case 1: path.addQuadCurveToPoint(RandomPoint(), controlPoint: RandomPoint())
        case 2: path.addCurveToPoint(RandomPoint(), controlPoint1: RandomPoint(), controlPoint2: RandomPoint())
        default: break;
    return path

Like the hack? Read the book.

Comments are closed.