public class SnowView extends View { private static final int NUM_SNOWFLAKES = 150; private static final int DELAY = 5;
private SnowFlake[] snowflakes;
public SnowView(Context context) { super(context); }
public SnowView(Context context, AttributeSet attrs) { super(context, attrs); }
public SnowView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); }
protected void resize(int width, int height) { Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.WHITE); paint.setStyle(Paint.Style.FILL); snowflakes = new SnowFlake[NUM_SNOWFLAKES]; for (int i = 0; i < NUM_SNOWFLAKES; i++) { snowflakes[i] = SnowFlake.create(width, height, paint); } }
@Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (w != oldw || h != oldh) { resize(w, h); } }
class SnowFlake { private static final float ANGE_RANGE = 0.1f; private static final float HALF_ANGLE_RANGE = ANGE_RANGE / 2f; private static final float HALF_PI = (float) Math.PI / 2f; private static final float ANGLE_SEED = 25f; private static final float ANGLE_DIVISOR = 10000f; private static final float INCREMENT_LOWER = 2f; private static final float INCREMENT_UPPER = 4f; private static final float FLAKE_SIZE_LOWER = 7f; private static final float FLAKE_SIZE_UPPER = 20f;
private final Random random; private final Point position; private float angle; private final float increment; private final float flakeSize; private final Paint paint;
public static SnowFlake create(int width, int height, Paint paint) { Random random = new Random(); int x = random.getRandom(width); int y = random.getRandom(height); Point position = new Point(x, y); float angle = random.getRandom(ANGLE_SEED) / ANGLE_SEED * ANGE_RANGE + HALF_PI - HALF_ANGLE_RANGE; float increment = random.getRandom(INCREMENT_LOWER, INCREMENT_UPPER); float flakeSize = random.getRandom(FLAKE_SIZE_LOWER, FLAKE_SIZE_UPPER); return new SnowFlake(random, position, angle, increment, flakeSize, paint); }
private boolean isInside(int width, int height) { int x = position.x; int y = position.y; return x >= -flakeSize - 1 && x + flakeSize <= width && y >= -flakeSize - 1 && y - flakeSize < height; }
Portions of this page are modifications based on work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License