美文网首页
自定义下雪动画(下)

自定义下雪动画(下)

作者: 黄烨1121 | 来源:发表于2017-11-10 01:11 被阅读0次

本章目录

  • Part One:雪花对象
  • Part Two:添加属性
  • Part Three:初始化数组
  • Part Four:绘制

在上一节中,我们完成了单个雪花的绘制,也就是把复杂问题简单化的过程。这一节我们开始在已经实现好的辑上,将其完善。

Part One:雪花对象

没有实体类,我们就无法创建多个雪花对象,写起来会非常麻烦。所以呢,要新建个bean包,创建SnowFlake实体类。

public class SnowFlake {
    private int width;//雪花宽度
    private int height;//雪花高度
    private int x;//雪花x轴坐标
    private int y;//雪花y轴坐标
    private int moveSpeedX;//雪花x轴移动速度
    private int moveSpeedY;//雪花y轴移动速度

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getMoveSpeedX() {
        return moveSpeedX;
    }

    public void setMoveSpeedX(int moveSpeedX) {
        this.moveSpeedX = moveSpeedX;
    }

    public int getMoveSpeedY() {
        return moveSpeedY;
    }

    public void setMoveSpeedY(int moveSpeedY) {
        this.moveSpeedY = moveSpeedY;
    }
}

暂时先写这6个属性,不够再加。

Part Two:添加属性

要做成下雪效果,就需要生成N个雪花,所以就需要创建雪花数组。之所以用数组不用集合,是因为每场下雪的雪花数量是一个固定值。
同时呢,我们可以将雪花数组的容量添加到自定义View属性中。
首先在attrs添加snowFlakeCount:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="SnowView">
        <attr name="minSize" format="integer"/>
        <attr name="maxSize" format="integer"/>
        <attr name="snowSrc" format="reference|integer"/>
        <attr name="moveX" format="integer"/>
        <attr name="moveY" format="integer"/>
        <attr name="snowFlakeCount" format="integer"/>
    </declare-styleable>
</resources>

然后在SnowView中初始化该属性

    private void initAttrs(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SnowView, 0, 0);
        minSize = typedArray.getInt(R.styleable.SnowView_minSize, 48);//获取最小值,默认48
        maxSize = typedArray.getInt(R.styleable.SnowView_maxSize, 72);//获取最大值,默认72
        int srcId = typedArray.getResourceId(R.styleable.SnowView_snowSrc, R.drawable.snow_flake);//获取默认图片资源ID
        snowSrc = BitmapFactory.decodeResource(getResources(), srcId);//根据资源ID生成Bitmap对象
        moveX = typedArray.getInt(R.styleable.SnowView_moveX, 10);//获取X轴移动速度
        moveY = typedArray.getInt(R.styleable.SnowView_moveY, 10);//获取Y轴移动速度
        if (minSize > maxSize){
            maxSize = minSize;
        }
        snowFlakeCount = typedArray.getInt(R.styleable.SnowView_snowFlakeCount, 100);//获取雪花数量,默认100
        typedArray.recycle();//TypedArray共享资源,资源回收
    }

最后在activity_main.xml中调用该属性

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#669900"
    tools:context="com.terana.mycustomview.MainActivity">

    <com.terana.mycustomview.cutstomview.SnowView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:minSize="16"
        app:maxSize="48"
        app:snowSrc="@drawable/snow_flake"
        app:moveX="10"
        app:moveY="10"
        app:snowFlakeCount="150"/>

</RelativeLayout>

Part Three:初始化数组

数组的容量设定好后,就可以在onSizeChanged方法里初始化数组的对象了,之所以在这里初始化,是因为在这里才能最终获取到View的高度和宽度。

    private SnowFlake[] snowFlakes;//雪花数组
    
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        snowFlakes = new SnowFlake[snowFlakeCount];
        boolean moveDirectionX = new Random().nextBoolean();
        //初始化雪花数组中的对象
        for (int i = 0; i < snowFlakes.length; i++){
            snowFlakes[i] = new SnowFlake();
            snowFlakes[i].setWidth(minSize + new Random().nextInt(maxSize - minSize));
            snowFlakes[i].setHeight(snowFlakes[i].getWidth());
            snowFlakes[i].setX(new Random().nextInt(w));
            snowFlakes[i].setY(-(new Random().nextInt(h)));
            if (moveDirectionX){
                snowFlakes[i].setMoveSpeedX(new Random().nextInt(4) + moveX);
            }else {
                snowFlakes[i].setMoveSpeedX(-(new Random().nextInt(4) + moveX));
            }
            snowFlakes[i].setMoveSpeedY(new Random().nextInt(4) + moveY);
        }
    }

Part Four:绘制

最后就是绘制了,我们把之前使用的值换成对象里的属性即可。
最终我们的SnowView的代码为:

package com.terana.mycustomview.cutstomview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.terana.mycustomview.R;
import com.terana.mycustomview.bean.SnowFlake;

import java.util.Random;

public class SnowView extends View{
    private int minSize;    //雪花大小随机值下限
    private int maxSize;    //雪花大小随机值上限
    private Bitmap snowSrc; //雪花的图案
    private int moveX;      //雪花每次移动的横向距离,也就是横向移动速度
    private int moveY;      //雪花每次移动的纵向距离,也就是纵向移动速度
    private Paint snowPaint;//雪花画笔
    private RectF rectF;//雪花放置区域
    private int snowFlakeCount;//雪花数量

    public SnowView(Context context) {
        this(context, null);
    }

    public SnowView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SnowView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public SnowView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initAttrs(context, attrs);
        initVariables();
    }

    private void initVariables() {
        snowPaint = new Paint();
        rectF = new RectF();
    }

    private void initAttrs(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SnowView, 0, 0);
        minSize = typedArray.getInt(R.styleable.SnowView_minSize, 48);//获取最小值,默认48
        maxSize = typedArray.getInt(R.styleable.SnowView_maxSize, 72);//获取最大值,默认72
        int srcId = typedArray.getResourceId(R.styleable.SnowView_snowSrc, R.drawable.snow_flake);//获取默认图片资源ID
        snowSrc = BitmapFactory.decodeResource(getResources(), srcId);//根据资源ID生成Bitmap对象
        moveX = typedArray.getInt(R.styleable.SnowView_moveX, 10);//获取X轴移动速度
        moveY = typedArray.getInt(R.styleable.SnowView_moveY, 10);//获取Y轴移动速度
        if (minSize > maxSize){
            maxSize = minSize;
        }
        snowFlakeCount = typedArray.getInt(R.styleable.SnowView_snowFlakeCount, 100);//获取雪花数量,默认100
        typedArray.recycle();//TypedArray共享资源,资源回收
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getDefaultMeasureSizes(getSuggestedMinimumWidth(), widthMeasureSpec, true);
        int height = getDefaultMeasureSizes(getSuggestedMinimumHeight(), heightMeasureSpec, false);
        setMeasuredDimension(width, height);
    }

    private int getDefaultMeasureSizes(int suggestedMinimumSize, int defaultMeasureSpec, boolean flag) {
        int result = suggestedMinimumSize;
        int specMode = MeasureSpec.getMode(defaultMeasureSpec);
        int specSize = MeasureSpec.getSize(defaultMeasureSpec);
        switch (specMode){
            case MeasureSpec.UNSPECIFIED:
                result = suggestedMinimumSize;
                break;
            case MeasureSpec.AT_MOST:
                if (flag){
                    result = snowSrc.getWidth() + getPaddingLeft() +getPaddingRight();
                }else {
                    result = snowSrc.getHeight() + getPaddingTop() +getPaddingBottom();
                }
                break;
            case MeasureSpec.EXACTLY:
                result = specSize;
                break;
        }
        return result;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawSnow(canvas);
    }

    private SnowFlake[] snowFlakes;//雪花数组

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        snowFlakes = new SnowFlake[snowFlakeCount];
        //初始化雪花数组中的对象
        for (int i = 0; i < snowFlakes.length; i++){
            snowFlakes[i] = new SnowFlake();
            boolean moveDirectionX = new Random().nextBoolean();
            snowFlakes[i].setWidth(minSize + new Random().nextInt(maxSize - minSize));
            snowFlakes[i].setHeight(snowFlakes[i].getWidth());
            snowFlakes[i].setX(new Random().nextInt(w));
            snowFlakes[i].setY(-(new Random().nextInt(h)));
            if (moveDirectionX){
                snowFlakes[i].setMoveSpeedX(new Random().nextInt(4) + moveX);
            }else {
                snowFlakes[i].setMoveSpeedX(-(new Random().nextInt(4) + moveX));
            }
            snowFlakes[i].setMoveSpeedY(new Random().nextInt(4) + moveY);
        }
    }

    private void drawSnow(Canvas canvas) {
        for (SnowFlake snowFlake: snowFlakes){
            rectF.left = snowFlake.getX();
            rectF.top = snowFlake.getY();
            rectF.right = rectF.left + snowFlake.getWidth();
            rectF.bottom = rectF.top + snowFlake.getHeight();
            canvas.drawBitmap(snowSrc, null, rectF, snowPaint);
        }
        getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                moveSknowFlake();
                invalidate();
            }
        }, 20);
    }

    private void moveSknowFlake() {
        int currentX;
        int currentY;
        for (SnowFlake snowFlake: snowFlakes) {
            currentX = snowFlake.getX() + snowFlake.getMoveSpeedX();
            currentY = snowFlake.getY() + snowFlake.getMoveSpeedY();
            //判断如果雪花移出屏幕左侧,右侧或者下侧,则回到起始位置重新开始
            if (currentX > getWidth() + snowSrc.getWidth() || currentX < 0 - snowSrc.getWidth() || currentY > getHeight()
                    + snowSrc.getHeight()){
                currentX = new Random().nextInt(getWidth());
                currentY = 0;
            }
            snowFlake.setX(currentX);
            snowFlake.setY(currentY);
        }
    }
}

效果为:


最终效果.gif

好了,下雪动画就这么完成了,有兴趣的话可以自己试试下雨动画。
再继续扩展就是用自定义View画雪,比如之前讲的画圆,一个白色实心圆其实就是雪球,然后将View转化为Bitmap,这个就留着自己试验了。

相关文章

网友评论

      本文标题:自定义下雪动画(下)

      本文链接:https://www.haomeiwen.com/subject/kvjvmxtx.html