Android-UI

android:自定义下雨下雪动画

2018-12-07  本文已影响0人  江左灬梅郎
圣诞节即将来临,PM给了一个需求:在A首页添加一个下雪的特效。事实上,有很多中方法可以实现。
1、用Lottie实现:让UI在AE上画一个动效,然后输出Json文件,前端直接在布局里设置就可以了。

这就又产生了和UI小姐姐的交配问题(哦不,说错了,交流问题)。UI小姐姐心里肯定是拒绝的,心里暗暗的说不定都把我按在她腿上摩擦了一千遍。不过,嘿嘿嘿~来啊,Who 怕 Who?

2、自定义View
国际惯例,先放效果图,如下:
雨雪

(gif图看起来可能有点卡顿的感觉,但是实际在真机上非常流畅,并无卡顿。)

代码依然很简单,来吧,老弟。

下雪:

SnowFlake.java

package com.ctrip.kotlin.view.snow;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;

/**
 * 雪花的类, 移动, 移出屏幕会重新设置位置.
 * <p/>
 * Created by w_yong on 18/12/4.
 */
public 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; // 半PI
    private static final float ANGLE_SEED = 25f; // 角度随机种子
    private static final float ANGLE_DIVISOR = 10000f; // 角度的分母

    // 雪花的移动速度
    private static final float INCREMENT_LOWER = 10f;
    private static final float INCREMENT_UPPER = 20f;

    // 雪花的大小
    private static final float FLAKE_SIZE_LOWER = 5f;
    private static final float FLAKE_SIZE_UPPER = 15f;

    private final SnowRandomGenerator mRandom; // 随机控制器
    private final Point mPosition; // 雪花位置
    private float mAngle; // 角度
    private final float mIncrement; // 雪花的速度
    private final float mFlakeSize; // 雪花的大小
    private final Paint mPaint; // 画笔

    private SnowFlake(SnowRandomGenerator random, Point position, float angle, float increment, float flakeSize, Paint paint) {
        mRandom = random;
        mPosition = position;
        mIncrement = increment;
        mFlakeSize = flakeSize;
        mPaint = paint;
        mAngle = angle;
    }

    public static SnowFlake create(int width, int height, Paint paint) {
        SnowRandomGenerator random = new SnowRandomGenerator();
        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);
    }

    // 绘制雪花
    public void draw(Canvas canvas) {
        int width = canvas.getWidth();
        int height = canvas.getHeight();
        move(width, height);
        canvas.drawCircle(mPosition.x, mPosition.y, mFlakeSize, mPaint);
    }

    // 移动雪花
    private void move(int width, int height) {
        double x = mPosition.x + (mIncrement * Math.cos(mAngle));
        double y = mPosition.y + (mIncrement * Math.sin(mAngle));

        mAngle += mRandom.getRandom(-ANGLE_SEED, ANGLE_SEED) / ANGLE_DIVISOR; // 随机晃动

        mPosition.set((int) x, (int) y);

        // 移除屏幕, 重新开始
        if (!isInside(width, height)) {
            reset(width);
        }
    }

    // 判断是否在其中
    private boolean isInside(int width, int height) {
        int x = mPosition.x;
        int y = mPosition.y;
        return x >= -mFlakeSize - 1 && x + mFlakeSize <= width && y >= -mFlakeSize - 1 && y - mFlakeSize < height;
    }

    // 重置雪花
    private void reset(int width) {
        mPosition.x = mRandom.getRandom(width);
        mPosition.y = (int) (-mFlakeSize - 1); // 最上面
        mAngle = mRandom.getRandom(ANGLE_SEED) / ANGLE_SEED * ANGE_RANGE + HALF_PI - HALF_ANGLE_RANGE;
    }
}


SnowRandomGenerator.java

package com.ctrip.kotlin.view.snow;

import java.util.Random;

/**
 * 随机生成器
 * <p/>
 * Created by w_yong on 18/12/4.
 */
public class SnowRandomGenerator {
    private static final Random RANDOM = new Random();

    // 区间随机
    public float getRandom(float lower, float upper) {
        float min = Math.min(lower, upper);
        float max = Math.max(lower, upper);
        return getRandom(max - min) + min;
    }

    // 上界随机
    public float getRandom(float upper) {
        return RANDOM.nextFloat() * upper;
    }

    // 上界随机
    public int getRandom(int upper) {
        return RANDOM.nextInt(upper);
    }
}


SnowView.java

package com.ctrip.kotlin.view.snow;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

/**
 * 雪花视图, DELAY时间重绘, 绘制NUM_SNOWFLAKES个雪花
 * <p/>
 * Created by w_yong on 18/12/4.
 */
public class SnowView extends View {

    private static final int NUM_SNOWFLAKES = 120; // 雪花数量
    private static final int DELAY = 5; // 延迟
    private SnowFlake[] mSnowFlakes; // 雪花

    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);
    }



    @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (w != oldw || h != oldh) {
            initSnow(w, h);
        }
    }

    private void initSnow(int width, int height) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); // 抗锯齿
        paint.setColor(Color.WHITE); // 白色雪花
        paint.setStyle(Paint.Style.FILL); // 填充;
        mSnowFlakes = new SnowFlake[NUM_SNOWFLAKES];
        for (int i = 0; i < NUM_SNOWFLAKES; ++i) {
            mSnowFlakes[i] = SnowFlake.create(width, height, paint);
        }
    }

    @Override protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (SnowFlake s : mSnowFlakes) {
            s.draw(canvas);
        }
        // 隔一段时间重绘一次, 动画效果
        getHandler().postDelayed(runnable, DELAY);
    }

    // 重绘线程
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            invalidate();
        }
    };
}

下雨:

RainFlake.java

package com.ctrip.kotlin.view.rian;

import android.graphics.Canvas;
import android.graphics.Paint;

/**
 * 雨滴的类, 移动, 移出屏幕会重新设置位置.
 */
public class RainFlake {

    // 雨滴的移动速度
    private static final float INCREMENT_LOWER = 20f;
    private static final float INCREMENT_UPPER = 40f;

    // 雨滴的大小
    private static final float FLAKE_SIZE_LOWER = 2f;
    private static final float FLAKE_SIZE_UPPER = 4f;

    private final float mIncrement; // 雨滴的速度
    private final float mFlakeSize; // 雨滴的大小
    private final Paint mPaint; // 画笔

    private Line mLine; // 雨滴

    private RainRandomGenerator mRandom;

    private RainFlake(RainRandomGenerator random, Line line, float increment, float flakeSize, Paint paint) {
        mRandom = random;
        mLine = line;
        mIncrement = increment;
        mFlakeSize = flakeSize;
        mPaint = paint;
    }

    //生成雨滴
    public static RainFlake create(int width, int height, Paint paint) {
        RainRandomGenerator random = new RainRandomGenerator();
        int [] nline;
        nline = random.getLine(width, height);

        Line line = new Line(nline[0], nline[1], nline[2], nline[3]);
        float increment = random.getRandom(INCREMENT_LOWER, INCREMENT_UPPER);
        float flakeSize = random.getRandom(FLAKE_SIZE_LOWER, FLAKE_SIZE_UPPER);
        return new RainFlake(random,line, increment, flakeSize, paint);
    }

    // 绘制雨滴
    public void draw(Canvas canvas) {
        int width = canvas.getWidth();
        int height = canvas.getHeight();
        drawLine(canvas, width, height);
    }

    /**
     * 改成线条,类似于雨滴效果
     * @param canvas
     * @param width
     * @param height
     */
    private void drawLine(Canvas canvas, int width, int height) {
        //设置线宽
        mPaint.setStrokeWidth(mFlakeSize);
        //y是竖直方向,就是下落
        double y1 = mLine.y1 + (mIncrement * Math.sin(1.5));
        double y2 = mLine.y2 + (mIncrement * Math.sin(1.5));

        //这个是设置雨滴位置,如果在很短时间内刷新一次,就是连起来的动画效果
        mLine.set(mLine.x1,(int) y1,mLine.x2 ,(int) y2);

        if (!isInsideLine(height)) {
            resetLine(width,height);
        }

        canvas.drawLine(mLine.x1, mLine.y1, mLine.x2, mLine.y2, mPaint);
    }

    // 判断是否在其中
    private boolean isInsideLine(int height) {
        return mLine.y1 < height && mLine.y2 < height;
    }

    // 重置雨滴
    private void resetLine(int width, int height) {
        int [] nline;
        nline = mRandom.getLine(width, height);
        mLine.x1 = nline[0];
        mLine.y1 = nline[1];
        mLine.x2 = nline[2];
        mLine.y2 = nline[3];
    }

}

RainRandomGenerator .java

package com.ctrip.kotlin.view.rian;

import java.util.Random;

/**
 * 随机生成器
 */
public class RainRandomGenerator {
    private final Random RANDOM = new Random();

    // 区间随机
    public float getRandom(float lower, float upper) {
        float min = Math.min(lower, upper);
        float max = Math.max(lower, upper);
        return getRandom(max - min) + min;
    }

    // 上界随机
    public float getRandom(float upper) {
        return RANDOM.nextFloat() * upper;
    }

    // 上界随机
    public int getRandom(int upper) {
        return RANDOM.nextInt(upper);
    }

    /**
     * 获得一个给定范围的随机整数
     * 可以负数到正数
     * @param smallistNum
     * @param BiggestNum
     * @return
     */
    public int getRandomNum(int smallistNum, int BiggestNum) {
        Random random = new Random();
        return (Math.abs(random.nextInt()) % (BiggestNum - smallistNum + 1))+ smallistNum;
    }

    //随机产生划线的起始点坐标和结束点坐标
    public int[] getLine(int height, int width) {
        int[] tempCheckNum = { 0, 0, 0, 0 };
        int temp = getRandomWidth(width);
        for (int i = 0; i < 4; i += 4) {
            tempCheckNum[i] = temp;
            tempCheckNum[i + 1] = (int) (Math.random() * height/4);
            tempCheckNum[i + 2] = temp;
            tempCheckNum[i + 3] = (int) (Math.random() * height/2);
        }
        return tempCheckNum;
    }

    public int getRandomWidth(int width){
        return (int) (Math.random() * width);
    }
}

Line.java

package com.ctrip.kotlin.view.rian;

public class Line {
    public int x1;
    public int y1;
    public int x2;
    public int y2;

    public Line() {
    }

    public Line(int x1, int y1,int x2, int y2) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
    }

    public Line(Line src) {
        this.x1 = src.x1;
        this.y1 = src.y1;
        this.x2 = src.x2;
        this.y2 = src.y2;
    }

    public void set(int x1, int y1,int x2, int y2) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
    }

    public final void negate() {
        x1 = -x1;
        y1 = -y1;
        x2 = -x2;
        y2 = -y2;
    }

    public final void offset(int dx, int dy) {
        x1 += dx;
        y1 += dy;
        x2 += dx;
        y2 += dy;
    }

    public final boolean equals(int x1, int y1,int x2, int y2) {
        return this.x1 == x1 && this.y1 == y1 && this.x2 == x2 && this.y2 == y2;
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof Line) {
            Line p = (Line) o;
            return this.x1 == p.x1 && this.y1 == p.y1 && this.x2 == p.x2 && this.y2 == p.y2;
        }
        return false;
    }

    @Override
    public String toString() {
        return "Line(" + x1 + ", " + y1 +  x2 + ", " + y2 +")";
    }
}

RainView.java

package com.ctrip.kotlin.view.rian;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import com.ctrip.kotlin.R;

/**
 * 雨滴视图, DELAY时间重绘, 绘制 NUM_SNOWFLAKES个雨滴
 */
public class RainView extends View {

    private static final int NUM_SNOWFLAKES = 100; // 雨滴数量
    private static final int DELAY = 5; // 延迟
    private RainFlake[] mSnowFlakes; // 雨滴

    public RainView(Context context) {
        super(context);
    }

    public RainView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RainView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (w != oldw || h != oldh) {
            initSnow(w, h);
        }
    }

    private void initSnow(int width, int height) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); // 抗锯齿
        paint.setColor(Color.WHITE); // 雨滴的颜色
        paint.setStyle(Paint.Style.FILL); // 填充;
        mSnowFlakes = new RainFlake[NUM_SNOWFLAKES];
        //mSnowFlakes所有的雨滴都生成放到这里面
        for (int i = 0; i < NUM_SNOWFLAKES; ++i) {
            mSnowFlakes[i] = RainFlake.create(width, height, paint);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //for返回SnowFlake
        for (RainFlake s : mSnowFlakes) {
            //然后进行绘制
            s.draw(canvas);
        }
        // 隔一段时间重绘一次, 动画效果
        getHandler().postDelayed(runnable, DELAY);
    }

    // 重绘线程
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //自动刷新
            invalidate();
        }
    };
}

最后,在XML中直接使用即可

   <com.ctrip.kotlin.view.snow.SnowView
            android:id="@+id/snowView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <com.ctrip.kotlin.view.rian.RainView
            android:id="@+id/rainView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

Over.

上一篇 下一篇

猜你喜欢

热点阅读