package com.example.myapplication;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Build;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
public class LoadingView extends View {
private Paint paint, paintShadow;
private float x, y;
private CountDownTimer timer;
private long totalTime = 400;//自由落体运动总时间(毫秒)
private long high = 800;//自由落体运动总距离
private long startY = 300;//自由落体开始的Y坐标
private boolean isDown = true;
private int currenttotalTime = 0;
private float viewG = 0; //重新计算View里的重力加速度值
private int timeCurr = 10;//UI刷新的时间间隔
public LoadingView(Context context) {
super(context);
initUtils();
}
public LoadingView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
initUtils();
}
public LoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initUtils();
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public LoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initUtils();
}
public void initUtils() {
paint = new Paint();// 初始化画笔
paint.setColor(Color.BLUE);
paintShadow = new Paint();
paintShadow.setColor(Color.GRAY);
float timeS = totalTime/1000f;//时间转化成秒 ,计算重力加速度
viewG = 2 * high / (timeS * timeS); // 此处1是因为1000毫秒换成1秒,1秒的平方还是1
y = startY;//初始坐标
x = 300;//初始坐标
float timeSCurr = timeCurr / 1000f;
timer = new CountDownTimer(totalTime, timeCurr) {
@Override
public void onTick(long millisUntilFinished) {
if (isDown) {
currenttotalTime += 1;//自由落体时间+1
} else {
currenttotalTime -= 1;//
}
//自由落体计算公式,因为时间是秒,距离单位是像素,所以要等比例缩放,像素和米的关系
y = viewG * timeSCurr * currenttotalTime * currenttotalTime * timeSCurr * 0.5f + startY;
invalidate();// 根据坐标重新绘制圆的位置
}
@Override
public void onFinish() {
isDown = !isDown;
if (isDown)
currenttotalTime = 0;
timer.start();
}
};
timer.start();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float totalHigh = (y - 300f) / high * 100f;
canvas.drawCircle(x, high - 100, totalHigh, paintShadow);
canvas.drawCircle(x, y, 100, paint);
}
}
写这种 动画其实很简单,找到变量点,圆的大小是不变的,变化的是圆心坐标,根据时间计算出落点的高度,然后画圆,然后每经过10毫秒刷新UI,就得到自由落体的动画了,给初学者学习用