自定义从上到下自由风吹飘落动画

自定义的自然飘落动画 飘落的图片自定义 自由替换,view跟之前的一样,直接复制直接用

/**
  * @Description: TODO 自定义图片从左上角往左下角飘动动画
  */
public class SnowFlyView extends View {
    private final int msgWhat = 0x01;
    public static final long DEFAULTDURATION = 300L;
    /**
     * the distance of snow start falling to the view top
     */
    private int initToTop;
    /**
     * the distance of snow start falling to the view left
     */
    private int initToLeft;
    /**
     * the distance of snow start falling to the view bottom
     */
    private int initToBottom;
    /**
     * the distance of snow start falling to the view right
     */
    private int initToRight;
    private float minScale;
    private float maxScale;
    private float xSpeed;
    private float ySpeed;
    private int snowCount;
    private long snowDuration;
    private List<Snow> snowList;
    private BitmapDrawable snowBitmap;
    private Matrix mtx = new Matrix();
    private ValueAnimator animator;
    private Random xRandom = new Random();
    private Random yRandom = new Random();
    private boolean isDelyStop;
    private boolean sendMsgable;
    /**
     * the range of snow start falling in the x direction
     */
    private float xWidth;
    /**
     * the range of snow start falling in the y direction
     */
    private float yHeight;
    private Context mContext;
    private ArrayList<Drawable> imageList;


    public SnowFlyView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SnowFlyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        initAttr(context, attrs);
        init();
    }

    private void initAttr(Context context, AttributeSet attrs) {
        TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.SnowFlyView);
        int initTo = attributes.getDimensionPixelSize(R.styleable.SnowFlyView_snow_initTo, 0);
        initToTop = attributes.getDimensionPixelSize(R.styleable.SnowFlyView_snow_initToTop, 0);
        initToLeft = attributes.getDimensionPixelSize(R.styleable.SnowFlyView_snow_initToLeft, 0);
        initToBottom = attributes.getDimensionPixelSize(R.styleable.SnowFlyView_snow_initToBottom, 0);
        initToRight = attributes.getDimensionPixelSize(R.styleable.SnowFlyView_snow_initToRight, 0);
        minScale = attributes.getFloat(R.styleable.SnowFlyView_snow_minScale, 1.0f);
        maxScale = attributes.getFloat(R.styleable.SnowFlyView_snow_maxScale, 1.0f);
        xSpeed = attributes.getFloat(R.styleable.SnowFlyView_snow_xSpeed, 0.0f);
        ySpeed = attributes.getFloat(R.styleable.SnowFlyView_snow_ySpeed, 100.0f);
        snowCount = attributes.getInt(R.styleable.SnowFlyView_snow_count, 20);
        snowDuration = attributes.getInt(R.styleable.SnowFlyView_snow_duration, 0);
        snowBitmap = (BitmapDrawable) attributes.getDrawable(R.styleable.SnowFlyView_snow_bitmap);

        if (0 != initTo)
            initToTop = initToLeft = initToBottom = initToRight = initTo;
        if (minScale <= 0.0f || minScale > maxScale)
            throw new IllegalArgumentException("The minScale is illegal");
        sendMsgable = snowDuration > DEFAULTDURATION;
        attributes.recycle();
    }

    private void init() {
        /**
         * close software/hardware
         */
        setLayerType(View.LAYER_TYPE_NONE, null);
        snowList = new ArrayList<>(snowCount);
        animator = ValueAnimator.ofFloat(0.0f, 1.0f);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setDuration(DEFAULTDURATION);
        animator.addUpdateListener(new animatorUpdateListenerImp());
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        xWidth = getWidth() - initToLeft - initToRight;
        yHeight = getHeight() - initToTop - initToBottom;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (int i = 0; i < snowList.size(); i++) {
            Snow snow = snowList.get(i);
            mtx.setTranslate(-snow.bpWidth / 2, -snow.bpHeight / 2);
            mtx.postTranslate(snow.bpWidth / 2 + snow.x, snow.bpHeight / 2 + snow.y);
            canvas.drawBitmap(snow.snowBitmap, mtx, null);
        }
    }

    /**
     * init snowList
     */
    private void initSnows() {
        if (null == snowBitmap) return;
        snowList.clear();
        for (int i = 0; i < snowCount; i++) {
            if(imageList!= null && imageList.size()>0){
                int who = (int) (Math.random() * imageList.size());
                snowBitmap = (BitmapDrawable)imageList.get(who);
            }
            Snow snow = new Snow(xSpeed, ySpeed, snowBitmap.getBitmap());
            snowList.add(snow);
        }
    }

    public void setImageDrawableList(ArrayList<Drawable> imageList){
        this.imageList = imageList;
    }

    /**
     * stop animation dely
     */
    public void stopAnimationDely() {
        removeMessages();
        this.isDelyStop = true;
    }

    /**
     * stop animation and clear snowList
     */
    public void stopAnimationNow() {
        removeMessages();
        snowList.clear();
        invalidate();
        animator.cancel();
    }

    /**
     * start animation
     */
    public void startAnimation() {
        this.isDelyStop = false;
        if (animator.isRunning())
            animator.cancel();
        if (sendMsgable) {
            removeMessages();
            handler.sendEmptyMessageDelayed(msgWhat, snowDuration);
        }
        initSnows();
        animator.start();
    }

    /**
     * set the duration of animation
     */
    public void setSnowDuration(long snowDuration) {
        this.snowDuration = snowDuration;
        sendMsgable = snowDuration > DEFAULTDURATION;
    }

    /**
     * back the state of animation
     */
    public boolean isRunning() {
        return animator.isRunning();
    }

    @Override
    protected void onDetachedFromWindow() {
        removeMessages();
        if (animator.isRunning())
            animator.cancel();
        super.onDetachedFromWindow();

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == msgWhat)
                isDelyStop = true;
        }
    };

    private void removeMessages() {
        if (handler.hasMessages(msgWhat))
            handler.removeMessages(msgWhat);
    }


    private class animatorUpdateListenerImp implements ValueAnimator.AnimatorUpdateListener {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {
            for (int i = 0; i < snowList.size(); i++) {
                Snow snow = snowList.get(i);
                snow.x += snow.xSpeed;
                snow.y += snow.ySpeed;
                if (snow.x < -snow.bpWidth || snow.x > getWidth()) {
                    /**
                     *  the snow falling to the sides
                     */
                    if (isDelyStop)
                        snowList.remove(i);
                    else {
                        snow.x = randomX(snow.bpWidth);
                        snow.y = randomY(snow.bpHeight);
                    }
                } else if (snow.y > getHeight()) {
                    /**
                     * the snow falling to the bottom
                     */
                    if (isDelyStop)
                        snowList.remove(i);
                    else {
                        snow.x = randomX(snow.bpWidth);
                        snow.y = randomY(snow.bpHeight);
                    }
                }
                Log.d("TAG", "snow.x:" + snow.x);
                Log.d("TAG", "snow.Y:" + snow.y);
            }
            /**
             * to prevent the animator running empty
             */
            if (snowList.size() <= 0 && animator.isRunning())
                animator.cancel();
            invalidate();
        }
    }

    class Snow {
        private float x;
        private float y;
        private float xSpeed;
        private float ySpeed;
        private int bpHeight;
        private int bpWidth;
        private Bitmap snowBitmap;
        private float BASESPEED = 100.0f;

        Snow(float xSpeed, float ySpeed, Bitmap snowBitmap) {
            float tempScale = minScale + (float) (Math.random() * (maxScale - minScale));
            this.bpHeight = (int) (snowBitmap.getHeight() * tempScale);
            this.bpWidth = (int) (snowBitmap.getWidth() * tempScale);
            this.x = randomX(bpWidth);
            this.y = randomY(bpHeight);
            /**
             * xDirection > 0 right falling
             * xDirection < 0 left falling
             * xDirection = 0 vertical falling
             */
            float xDirection = 1.0f - (float) (Math.random() * 2.0f);
//            this.xSpeed = xSpeed * xDirection / BASESPEED;
            this.xSpeed = (xSpeed + (xSpeed * 6) * (float) Math.random()) / BASESPEED;
            this.ySpeed = (ySpeed + (ySpeed * 3) * (float) Math.random()) / BASESPEED;
            this.snowBitmap = Bitmap.createScaledBitmap(snowBitmap, bpWidth, bpHeight, true);
        }
    }

    /**
     * the x coordinate
     */
    private float randomX(int bpWidth) {
        return initToLeft + xRandom.nextFloat() * (xWidth - bpWidth) - 1000;
    }

    /**
     * the y coordinate
     */
    private float randomY(int bpHeight) {
        return (initToTop + yRandom.nextFloat() * (yHeight - bpHeight)) - 800;
    }
}

动画的属性定义

<declare-styleable name="SnowFlyView">
        <attr name="snow_initTo" format="dimension" />
        <attr name="snow_initToTop" format="dimension" />
        <attr name="snow_initToLeft" format="dimension" />
        <attr name="snow_initToBottom" format="dimension" />
        <attr name="snow_initToRight" format="dimension" />
        <attr name="snow_minScale" format="float" />
        <attr name="snow_maxScale" format="float" />
        <attr name="snow_count" format="integer" />
        <attr name="snow_duration" format="integer" />
        <attr name="snow_xSpeed" format="float" />
        <attr name="snow_ySpeed" format="float" />
        <attr name="snow_bitmap" format="reference" />
    </declare-styleable>

使用方法也很简单,在你要用的页面中放这个view空间 范围可以自己定, 使用方法如下,自己定义图片 飘落速度 等

        flowerFlaySfv.setSnowDuration(300);
        ArrayList<Drawable> imageList = new ArrayList<>();
        imageList.add(mContext.getResources().getDrawable(R.mipmap.snowflake1,null));
        imageList.add(mContext.getResources().getDrawable(R.mipmap.snowflake2,null));
        imageList.add(mContext.getResources().getDrawable(R.mipmap.snowflake3,null));
        imageList.add(mContext.getResources().getDrawable(R.mipmap.snowflake4,null));
        imageList.add(mContext.getResources().getDrawable(R.mipmap.snowflake5,null));
        imageList.add(mContext.getResources().getDrawable(R.mipmap.snowflake6,null));
        flowerFlaySfv.setImageDrawableList(imageList);
        flowerFlaySfv.startAnimation();

ok 就这样,自己想飘落什么飘落什么 ,当然如果觉得 风力太小 可以修改自定义控件,这个就不讲了 自己研究下,自己学会的才是自己的。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,245评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,749评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,960评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,575评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,668评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,670评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,664评论 3 415
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,422评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,864评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,178评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,340评论 1 344
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,015评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,646评论 3 323
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,265评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,494评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,261评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,206评论 2 352