仿微信弹出“生日快乐”类动画
今天看到微信的动画蛮有意思,刚好最近也在研究GUI绘图,于是写了个DEMO。
其实不难,分为两部分处理就好了,其一是动画的子项Item:
- 该类动画少不了Random随机数,在初始化时创建
public void init(Context context) {
//获取BitMap对象
mBitmap = BitmapFactory.decodeResource(context.getResources(), fallSrc);
//初始化Random
Random r = new Random();
//Item的横坐标
x = r.nextInt(parentWidth-mBitmap.getWidth());
//动画的加速度
accelerlateSpeed = ((100f + (float) r.nextInt(100)) / 100000f);
//Item的纵左标
startY = r.nextInt(30);
//计算Item动画总时间
int t = (int) Math.cbrt(parentHeight * 2 / accelerlateSpeed);
//出现时间(随机)
if (r.nextBoolean())
startTime = r.nextInt(t/2 );
}
然后是子项Item的动画逻辑
//出现时间逐渐接近 if (startTime > 0) { startTime-=1; return; } if (visible) { t += 1; //计算纵左标 y = (int) (accelerlateSpeed * t * t * t / 2)+startY; //超出屏幕高度则不再绘制 if (y >= parentHeight) visible = false; } }
每次绘制调用下面的方法就好了
public void draw(Canvas canvas) {
if (visible&&y>0&&startTime==0)
canvas.drawBitmap(mBitmap, x, y, mPaint);
}
- 其二在控制类里面,使用子线程绘制
class AnimationThread extends Thread {
@Override
public void run() {
//初始化
init(getContext());
while (running) {
//动画逻辑部分
animationLogic();
postInvalidate();
try {
Thread.sleep(1000/60);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
DEMO还用到了自定义属性 itemNum和fallSrc
其中itemNum代表子项的数目,默认20
- fallSrc代表图片
例如:
<com.zmf.fallanimation.demo.FallAnimationView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fall:itemNum="20"
fall:fallSrc="@mipmap/ic_fall"
/>