自定义View——天气下雨效果

项目要实现下雨效果,在StylingAndroid中发现一篇有关下雪的效果,稍作修改,便可以实现下雨效果:
原地址:https://blog.stylingandroid.com/snowfall/

public class RainView extends View {
    private static final int NUM_RAIN_FLAKES = 100;
    private static final int DELAY = 5;

    private RainFlake[] rainflakes;

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

    protected void resize(int width, int height) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.WHITE);
        paint.setStyle(Paint.Style.FILL);
        rainflakes = new RainFlake[NUM_RAIN_FLAKES];
        for (int i = 0; i < NUM_RAIN_FLAKES; i++) {
            rainflakes[i] = RainFlake.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);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (RainFlake rainFlake : rainflakes) {
            rainFlake.draw(canvas);
        }
        getHandler().postDelayed(runnable, DELAY);
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            invalidate();
        }
    };
}
class RainFlake {
    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 = 4f;
    private static final float INCREMENT_UPPER = 6f;
    private static final float FLAKE_SIZE_LOWER = 7f;
    private static final float FLAKE_SIZE_UPPER = 25f;

    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 RainFlake 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 RainFlake(random, position, angle, increment, flakeSize, paint);
    }

    RainFlake(Random random, Point position, float angle, float increment, float flakeSize,
              Paint paint) {
        this.random = random;
        this.position = position;
        this.angle = angle;
        this.increment = increment;
        this.flakeSize = flakeSize;
        this.paint = paint;
    }

    private void move(int width, int height) {
    //    double x = position.x + (increment * Math.cos(angle));
        double x = position.x;
        double y = position.y + (increment * Math.sin(angle));

        angle += random.getRandom(-ANGLE_SEED, ANGLE_SEED) / ANGLE_DIVISOR;

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

        if (!isInside(width, height)) {
            reset(width);
        }
    }

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

    private void reset(int width) {
        position.x = random.getRandom(width);
        position.y = (int) (-flakeSize - 1);
        angle = random.getRandom(ANGLE_SEED) / ANGLE_SEED * ANGE_RANGE + HALF_PI - HALF_ANGLE_RANGE;
    }

    public void draw(Canvas canvas) {
        int width = canvas.getWidth();
        int height = canvas.getHeight();
        move(width, height);
        canvas.drawLine(position.x, position.y, position.x,position.y+flakeSize, paint);
    }
}
class Random {
    private static final java.util.Random RANDOM = new java.util.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);
    }

}
效果开始前先做个热身( ˘•灬•˘ )自己实现比较容易,但是到了要出博客整理思路,总结要点的时候就挠头,不知云所以,所以最简单的还是 Read the fucking source code如果对安卓UI有兴趣的朋友可以加我好友互相探讨,这有很多自定义view可以参考思路思路比较简单,整个view无非两样东西云雨滴这又包含两部分动画,一部分是云的左右移动动画,一部分是雨滴移动动画 那我们这可以自定义一些属性,如果对自定义属性还不太了解的同学,搜下百度哈<resources>     <declare-styleable name="RainyView">         <!--雨滴的颜色-->         <attr name="raindrop_color" format="color"></attr>         <!--左边云的颜色-->         <attr name="left_cloud_color" format="color"></attr>         <!--右边云的颜色-->         <attr name="right_cloud_color" format="color"></attr>         <!-可同时存在的雨滴的最大数量-->         <attr name="raindrop_max_number" format="integer"></attr>         <!--每个雨滴之间创建的时间间隔-->         <attr name="raindrop_creation_interval" format="integer"></attr>         <!--每个雨滴的最小长度-->         <attr name="raindrop_min_length" format="integer"></attr>         <!--每个雨滴的最大长度-->         <attr name="raindrop_max_length" format="integer"></attr>         <!--雨滴的大小-->         <attr name="raindrop_size" format="integer"></attr>         <!--雨滴的最小移动速度-->         <attr name="raindrop_min_speed" format="float"></attr>         <!--雨滴的最大移动速度-->         <attr name="raindrop_max_speed" format="float"></attr>         <!--雨滴的斜率-->         <attr name="raindrop_slope" format="float"></attr>     </declare-styleable> </resources>画云云怎么画?云的形状不可胜举,我这只实现了一种简单的形状:那我们如何通过画笔将其画出来:1.首先,我们先画底部,底部是一个圆角的矩形,通过下面方法绘制添加圆角矩形path.addRoundRect(RectF rect, float rx, float ry, Direction dir) 2.在该圆角的矩形的基础上,再画两个圆,左边的为小圆,右边的为大圆,这样就产生了一个最简单的云的图形, 在设置了以下代码之后paint.setStyle(Paint.Style.FILL);云的效果如下:我们把这个云作为左边的云,那么右边的云怎么画?很简单,因为我们这用path来装载了这个云的路径,通过以下方法,mComputeMatrix.preTranslate(rightCloudTranslateX, -calculateRect.height() * (1 - CLOUD_SCALE_RATIO) / 2); mComputeMatrix.postScale(CLOUD_SCALE_RATIO, CLOUD_SCALE_RATIO, rightCloudCenterX, leftCloudEndY); mLeftCloudPath.transform(mComputeMatrix, mRightCloudPath);将这个云的path移动,缩小,并将其路径转换到mRightCloudPath即可在onDraw()的时候,调用以下方法就可以描绘路径了canvas.drawPath()接下来我们来实现云的动画,我们由上面已经了解到:/**  * Transform the points in this path by matrix, and write the answer  * into dst. If dst is null, then the the original path is modified.  *  * @param matrix The matrix to apply to the path  * @param dst    The transformed path is written here. If dst is null,  *               then the the original path is modified  */ public void transform(Matrix matrix, Path dst) {     long dstNative = 0;     if (dst != null) {         dst.isSimplePath = false;         dstNative = dst.mNativePath;     }     nTransform(mNativePath, matrix.native_instance, dstNative); }该方法可以将一个path进行matrix转换,即矩阵转换,因此我们可以通过方法matrix.postTranslate来实现平移动画,即创建一个循环动画,通过postTranslate来设置动画值就可以了,这左边的云在右边的云之上,因此先画右边的云。mComputeMatrix.reset(); mComputeMatrix.postTranslate((mMaxTranslationX / 2) * mRightCloudAnimatorValue, 0); mRightCloudPath.transform(mComputeMatrix, mComputePath); canvas.drawPath(mComputePath, mRightCloudPaint); mComputeMatrix.reset(); mComputeMatrix.postTranslate(mMaxTranslationX * mLeftCloudAnimatorValue, 0); mLeftCloudPath.transform(mComputeMatrix, mComputePath); canvas.drawPath(mComputePath, mLeftCloudPaint);画雨滴首先我们要知道一点是,所有的雨滴都是随机产生的,而产生的值,可以根据上面的自定义属性指定,也可以使用自定义的值,我们先定义一个雨滴类private class RainDrop{     float speedX;  //雨滴x轴移动速度     float speedY;   //雨滴y轴移动速度     float xLength; //雨滴的x轴长度     float yLength; //雨滴的y轴长度     float x;        //雨滴的x轴坐标     float y;        //雨滴的y轴坐标     float slope; //雨滴的斜率 }关于上面参数,这画张图来示例:关于斜率 我这开放了一个设置斜率的接口,代表雨滴的一个倾斜度,可以看到下图的雨滴都是倾斜的,就是通过斜率来设置这个倾斜度 斜率:表示一条直线(或曲线的切线)关于(横)坐标轴倾斜程度的量。它通常用直线(或曲线的切线)与(横)坐标轴夹角的正切,或两点的纵坐标之差与横坐标之差的比来表示。该直线的斜率为k=(y1-y2)/(x1-x2)我这使用了固定的斜率,使所有的雨滴方向一致,如果想将其改为随机值的同学,可以下载源码自行修改。在创建雨滴对象的时候,以下步骤使我们需要做的:斜率赋值(我这是指定的,因此不用计算随机斜率)计算x轴、y轴移动速度随机值计算雨滴长度随机值(同时计算x轴,y轴长度值)计算x,y坐标随机值(为了营造雨滴更好的出场效果,这设置了y轴的起点坐标为y-雨滴y轴长度)创建雨滴对象后,我们有了想要的参数,我们可以canvas.drawLine来画雨滴canvas.drawLine(rainDrop.x, rainDrop.y,             rainDrop.slope > 0 ? rainDrop.x   rainDrop.xLength : rainDrop.x - rainDrop.xLength,             rainDrop.y   rainDrop.yLength,             mRainPaint);这需要注意以下,为什么canvas.drawLine中的stopX参数要设置为rainDrop.slope > 0 ? rainDrop.x   rainDrop.xLength : rainDrop.x - rainDrop.xLength这是因为,我们的雨滴是一直往下移动即y是增加的,我们上面知道斜率公式为:k=(y1-y2)/(x1-x2)即y1-y2肯定是大于0的,因此当斜率小于0的时候,雨滴是这样的,即x1-x2 < 0 当斜率大于0的时候,雨滴是这样的,即x1-x2 > 0 雨滴动画,由于每一个雨滴对象参数已经定义,在进行动画的时候,只需要根据速度,设置x、y轴的下一个点的坐标就行了if (rainDrop.slope >= 0) {         rainDrop.x  = rainDrop.speedX;     }else{         rainDrop.x -= rainDrop.speedX;     } rainDrop.y  = rainDrop.speedY;优化我们知道,在频繁的创建雨滴的时候,如果每次都创建新对象的话, 可能会增加不必要的内存使用,而且很容易引起频繁的gc,甚至是内存抖动。因此这我增加了一个回收功能//首先判断栈中是否存在回收的对象,若存在,则直接复用,若不存在,则创建一个新的对象 private RainDrop obtainRainDrop(){      if (mRecycler.isEmpty()){          return new RainDrop();      }      return mRecycler.pop();  } //回收到一个栈面,若这个栈数量超过最大可显示数量,则pop private void recycle(RainDrop rainDrop){     if (rainDrop == null){         return;     }     if (mRecycler.size() >= mRainDropMaxNumber){         mRecycler.pop();     }     mRecycler.push(rainDrop); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值