Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a 'snow like' effect to a UIView

I am currently making a Christmas application and I would like it to 'snow' on the screen.

So far I have this code:

Snow.swift

import Foundation
import UIKit

@IBDesignable
class Snow:UIView
{

    var viewHeight = CGFloat(0)
    /*
    required init(coder aDecoder: NSCoder) {
        //Initilse UIView
        super.init(coder: aDecoder)!
    }
    */

    override func drawRect(rect: CGRect) {
        let path = UIBezierPath(ovalInRect: rect)
        UIColor.whiteColor().setFill()
        path.fill()
    }
}

ViewController.swift

@IBDesignable
class ViewController: UIViewController {

    @IBInspectable var BgColor:UIColor = UIColor.whiteColor()

    var animator: UIDynamicAnimator? = nil;
    var gravity = UIGravityBehavior()


    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = BgColor
        /*listSubviewsOfView(self.view)*/ /*Not needed to answer this*/
        var snow = Snow(frame: CGRect(x: 0, y: 0, width: 5, height: 5))
        snow.opaque = false
        self.view.addSubview(snow)

        animator = UIDynamicAnimator(referenceView:self.view);
        animator?.addBehavior(gravity)

        gravity.addItem(snow)
        let direction = CGVectorMake(0.0, 1.0)
        gravity.gravityDirection = direction
    }


    /*Not needed to solve this*/
    /*
    func listSubviewsOfView(views: UIView) {
        var index = 0
        let randomNumbers = [Int](1...24).shuffle()
        for view in views.subviews
        {
            if let _ = view.restorationIdentifier
            {
                view.setValue(String(Int(randomNumbers[index])), forKey: "updateText")
                index++
            }
            if index == randomNumbers.count {
                break
            }
        }
    }
    */

}

This is what it currently looks like (in the iPhone 5 simulator)

enter image description here

As you can see, the UIView falls to the bottom of the screen too fast (falls like a brick instead of snow).

How would I get the 'snow' to fall slower along with a wind effect?

like image 444
iProgram Avatar asked Nov 28 '15 12:11

iProgram


1 Answers

I would do this with an SKEmitterNode. There is also a graphical editor available in SpriteKit, where you can easily create a snow effect. Here's a short tutorial about this: enter link description here

like image 95
Stefan Avatar answered Nov 15 '22 07:11

Stefan