一、前言
本篇和上一篇《Android 粒子喷泉效果》一样,通过Canvas 2D坐标系实现粒子效果。上一篇我们着重讲了粒子效果的三个要素:起始点、矢量速度、符合运动学方程。当然有人会疑惑,终点不重要么 ?实际上大部分情况下,只有在防止跑出边界的情况下才会计算终点,本篇也会计算终点,防止跑出边界。
效果预览
无中心版本
有中心版本
二、实现
2.1 均匀分布
我们首要解决的问题是计算出粒子运动方向,保证粒子能正常扩散到目标范围和区域,另外还有保证粒子尽可能随机和均匀分布在任意方向。
方法是:
粒子扩散的范围是一个圆的范围内,我们要尽可能利用圆的旋转半径和夹角之间的关系,属于高中数学知识。另外也要控制粒子的数量,防止堆叠过多的问题。
ini
int t = i % 12;
double degree = random.nextFloat() * 30 + t * 30; // 12等分圆,没等分都保证产生粒子
// 360 /12 = 30 ,意味着每等分30度区域内需要产生一定的粒子
2.2 速度计算
我们上一篇说过,计算出速度是最难的,要结合场景,这里我们采样计算终点的方式,目的有2个,限制粒子运动出大圆,限制时间。
ini
float minRadius = maxRadius * 1f / 2f;
double radians = Math.toRadians(degree);
int radius = (int) (random.nextFloat() * maxRadius / 2f);
float x = (float) (Math.cos(radians) * (radius + minRadius));
float y = (float) (Math.sin(radians) * (radius + minRadius));
float speedX = (x - 0) / dt;
float speedY = (y - 0) / dt;
2.3 颜色
颜色选择自己喜欢的就可以,我喜欢五彩缤纷,所以随机生成
scss
int color = argb(random.nextFloat(), random.nextFloat(), random.nextFloat());
2.4 定义粒子对象
java
static class Star {
private final boolean fromCenter;
private final int color;
private double radians;
private float r;
float speedX;
float speedY;
long startTime;
Path path = new Path();
int type = TYPE_QUAD;
public Star(float speedX, float speedY, long clockTime, float r, double radians, int color, boolean fromCenter, int type) {
this.speedX = speedX;
this.speedY = speedY;
this.startTime = clockTime;
this.r = r;
this.radians = radians;
this.fromCenter = fromCenter;
this.color = color;
this.type = type;
}
public void draw(Canvas canvas,Paint paint,long clockTime){
}
}
2.4 基础骨架
ini
public void drawBase(Canvas canvas, Paint paint, long clockTime) {
long costTime = clockTime - startTime;
float dx = speedX * costTime;
float dy = speedY * costTime;
double currentRadius = Math.sqrt(dx * dx + dy * dy);
paint.setColor(color);
if (currentRadius > 0) {
double asin = Math.asin(r / currentRadius);
//利用反三角函数计算出切线与圆的夹角
int t = 1;
for (int i = 0; i < 2; i++) {
double aspectRadius = Math.abs(Math.cos(asin) * currentRadius); //切线长度
float ax = (float) (aspectRadius * Math.cos(radians + asin * t));
float ay = (float) (aspectRadius * Math.sin(radians + asin * t));
if (fromCenter) {
canvas.drawLine(0, 0, ax, ay, paint);
} else {
canvas.drawLine(dx / 3, dy / 3, ax, ay, paint);
}
t = -1;
}
}
canvas.drawCircle(dx, dy, r, paint);
}
2.5 进一步优化
ini
public void drawCircleCCW(Canvas canvas, Paint paint, long clockTime) {
long costTime = clockTime - startTime;
float dx = speedX * costTime;
float dy = speedY * costTime;
double currentRadius = Math.sqrt(dx * dx + dy * dy);
path.reset();
if (currentRadius > 0) {
if (fromCenter) {
path.moveTo(0, 0);
} else {
path.moveTo(dx / 3, dy / 3);
}
//1、利用反三角函数计算出小圆切线与所有小圆原点与(0,0)点的夹角
double asin = Math.asin(r / currentRadius);
//2、计算出切线长度
double aspectRadius = Math.abs(Math.cos(asin) * currentRadius);
float axLeft = (float) (aspectRadius * Math.cos(radians - asin));
float ayLeft = (float) (aspectRadius * Math.sin(radians - asin));
path.lineTo(axLeft, ayLeft);
float axRight = (float) (aspectRadius * Math.cos(radians + asin));
float ayRight = (float) (aspectRadius * Math.sin(radians + asin));
path.lineTo(axRight, ayRight);
path.addCircle(dx, dy, r, Path.Direction.CCW);
}
path.close();
paint.setColor(color);
canvas.drawPath(path, paint);
}
有点样子了,但是问题是,Path动画并没有和粒子圆点闭合,这样就会有问题,后续如果要使用Shader着色 (为啥要用Shader着色,主要是火焰效果很难画出来,还得借助一些其他工具),必然产生不均匀问题。为了实现开头的效果,最初是计算切线和小圆的夹角让Path闭合,但是计算量和难度太大了,直接使用贝塞尔曲线更省事。
ini
public void drawQuad(Canvas canvas, Paint paint, long clockTime) {
long costTime = clockTime - startTime;
float dx = speedX * costTime;
float dy = speedY * costTime;
double currentRadius = Math.sqrt(dx * dx + dy * dy);
path.reset();
if (currentRadius > 0) {
if (fromCenter) {
path.moveTo(0, 0);
} else {
path.moveTo(dx / 3, dy / 3);
}
//1、利用反三角函数计算出小圆切线与所有小圆原点与(0,0)点的夹角
double asin = Math.asin(r / currentRadius);
//2、计算出切线长度
double aspectRadius = Math.abs(Math.cos(asin) * currentRadius);
float axLeft = (float) (aspectRadius * Math.cos(radians - asin));
float ayLeft = (float) (aspectRadius * Math.sin(radians - asin));
path.lineTo(axLeft, ayLeft);
float axRight = (float) (aspectRadius * Math.cos(radians + asin));
float ayRight = (float) (aspectRadius * Math.sin(radians + asin));
float cx = (float) (Math.cos(radians) * (currentRadius + 2 * r));
float cy = (float) (Math.sin(radians) * (currentRadius + 2 * r));
//如果使用三角函数计算切线可能很复杂,这里使用贝塞尔曲线简化逻辑
path.quadTo(cx, cy, axRight, ayRight);
path.lineTo(axRight, ayRight);
}
path.close();
paint.setColor(color);
canvas.drawPath(path, paint);
}
三、全部代码
ini
public class FireworksView extends View implements Runnable {
private static final long V_SYNC_TIME = 30;
private final DisplayMetrics mDM;
private TextPaint mArcPaint;
private long displayTime = 500L; //控制时间,防止逃出边界
private long clockTime = 0;
private boolean isNextDrawingTimeScheduled = false;
private TextPaint mDrawerPaint = null;
private Random random;
final int maxStartNum = 50;
Star[] stars = new Star[maxStartNum];
private boolean isRefresh = true;
public static final int TYPE_BASE = 1;
public static final int TYPE_QUAD = 2;
public static final int TYPE_RECT = 3;
public static final int TYPE_CIRCLE_CCW = 4;
public FireworksView(Context context) {
this(context, null);
}
public FireworksView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FireworksView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mDM = getResources().getDisplayMetrics();
initPaint();
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startPlay();
}
});
}
public static int argb(float red, float green, float blue) {
return ((int) (1 * 255.0f + 0.5f) << 24) |
((int) (red * 255.0f + 0.5f) << 16) |
((int) (green * 255.0f + 0.5f) << 8) |
(int) (blue * 255.0f + 0.5f);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
if (widthMode != MeasureSpec.EXACTLY) {
widthSize = mDM.widthPixels / 2;
}
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (heightMode != MeasureSpec.EXACTLY) {
heightSize = widthSize / 2;
}
random = new Random(SystemClock.uptimeMillis());
setMeasuredDimension(widthSize, heightSize);
}
public float dp2px(float dp) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, mDM);
}
public float sp2px(float dp) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, dp, mDM);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
if (width <= 10 || height <= 10) {
return;
}
int saveCount = canvas.save();
int maxRadius = Math.min(width, height) / 2;
canvas.translate(width / 2, height / 2);
long clockTime = getClockTime();
if (isRefresh) {
float dt = 1000;
float r = 5;
for (int i = 0; i < maxStartNum; i++) {
int t = i % 12;
double degree = random.nextFloat() * 30 + t * 30; // 12等分圆
float minRadius = maxRadius * 1f / 2f;
double radians = Math.toRadians(degree);
int radius = (int) (random.nextFloat() * maxRadius / 2f);
float x = (float) (Math.cos(radians) * (radius + minRadius));
float y = (float) (Math.sin(radians) * (radius + minRadius));
float speedX = (x - 0) / dt;
float speedY = (y - 0) / dt;
int color = argb(random.nextFloat(), random.nextFloat(), random.nextFloat());
stars[i] = new Star(speedX, speedY, clockTime, r, radians, color, false, TYPE_QUAD);
}
isRefresh = false;
}
for (int i = 0; i < maxStartNum; i++) {
Star star = stars[i];
star.draw(canvas, mDrawerPaint, clockTime);
}
if (!isNextDrawingTimeScheduled) {
isNextDrawingTimeScheduled = true;
postDelayed(this, V_SYNC_TIME);
}
canvas.restoreToCount(saveCount);
}
@Override
public void run() {
isNextDrawingTimeScheduled = false;
clockTime += 32;
if (clockTime > displayTime) {
clockTime = displayTime;
}
postInvalidate();
}
private long getClockTime() {
return clockTime;
}
public void startPlay() {
clockTime = 0;
isRefresh = true;
removeCallbacks(this);
run();
}
private void initPaint() {
// 实例化画笔并打开抗锯齿
mArcPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
mArcPaint.setAntiAlias(true);
mArcPaint.setStyle(Paint.Style.STROKE);
mArcPaint.setStrokeCap(Paint.Cap.ROUND);
mDrawerPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
mDrawerPaint.setAntiAlias(true);
mDrawerPaint.setStyle(Paint.Style.FILL);
mDrawerPaint.setStrokeCap(Paint.Cap.ROUND);
}
static class Star {
private final boolean fromCenter;
private final int color;
private double radians;
private float r;
float speedX;
float speedY;
long startTime;
Path path = new Path();
int type = TYPE_QUAD;
public Star(float speedX, float speedY, long clockTime, float r, double radians, int color, boolean fromCenter, int type) {
this.speedX = speedX;
this.speedY = speedY;
this.startTime = clockTime;
this.r = r;
this.radians = radians;
this.fromCenter = fromCenter;
this.color = color;
this.type = type;
}
public void draw(Canvas canvas, Paint paint, long clockTime) {
switch (type) {
case TYPE_BASE:
drawBase(canvas, paint, clockTime);
break;
case TYPE_RECT:
drawRect(canvas, paint, clockTime);
break;
case TYPE_CIRCLE_CCW:
drawCircleCCW(canvas, paint, clockTime);
break;
case TYPE_QUAD:
drawQuad(canvas, paint, clockTime);
break;
}
}
public void drawQuad(Canvas canvas, Paint paint, long clockTime) {
long costTime = clockTime - startTime;
float dx = speedX * costTime;
float dy = speedY * costTime;
double currentRadius = Math.sqrt(dx * dx + dy * dy);
path.reset();
if (currentRadius > 0) {
if (fromCenter) {
path.moveTo(0, 0);
} else {
path.moveTo(dx / 3, dy / 3);
}
//1、利用反三角函数计算出小圆切线与所有小圆原点与(0,0)点的夹角
double asin = Math.asin(r / currentRadius);
//2、计算出切线长度
double aspectRadius = Math.abs(Math.cos(asin) * currentRadius);
float axLeft = (float) (aspectRadius * Math.cos(radians - asin));
float ayLeft = (float) (aspectRadius * Math.sin(radians - asin));
path.lineTo(axLeft, ayLeft);
float axRight = (float) (aspectRadius * Math.cos(radians + asin));
float ayRight = (float) (aspectRadius * Math.sin(radians + asin));
float cx = (float) (Math.cos(radians) * (currentRadius + 2 * r));
float cy = (float) (Math.sin(radians) * (currentRadius + 2 * r));
//如果使用三角函数计算切线可能很复杂,这里使用贝塞尔曲线简化逻辑
path.quadTo(cx, cy, axRight, ayRight);
path.lineTo(axRight, ayRight);
}
path.close();
paint.setColor(color);
canvas.drawPath(path, paint);
}
public void drawCircleCCW(Canvas canvas, Paint paint, long clockTime) {
long costTime = clockTime - startTime;
float dx = speedX * costTime;
float dy = speedY * costTime;
double currentRadius = Math.sqrt(dx * dx + dy * dy);
path.reset();
if (currentRadius > 0) {
if (fromCenter) {
path.moveTo(0, 0);
} else {
path.moveTo(dx / 3, dy / 3);
}
//1、利用反三角函数计算出小圆切线与所有小圆原点与(0,0)点的夹角
double asin = Math.asin(r / currentRadius);
//2、计算出切线长度
double aspectRadius = Math.abs(Math.cos(asin) * currentRadius);
float axLeft = (float) (aspectRadius * Math.cos(radians - asin));
float ayLeft = (float) (aspectRadius * Math.sin(radians - asin));
path.lineTo(axLeft, ayLeft);
float axRight = (float) (aspectRadius * Math.cos(radians + asin));
float ayRight = (float) (aspectRadius * Math.sin(radians + asin));
path.lineTo(axRight, ayRight);
path.addCircle(dx, dy, r, Path.Direction.CCW);
}
path.close();
paint.setColor(color);
canvas.drawPath(path, paint);
}
public void drawBase(Canvas canvas, Paint paint, long clockTime) {
long costTime = clockTime - startTime;
float dx = speedX * costTime;
float dy = speedY * costTime;
double currentRadius = Math.sqrt(dx * dx + dy * dy);
paint.setColor(color);
if (currentRadius > 0) {
double asin = Math.asin(r / currentRadius);
//利用反三角函数计算出切线与圆的夹角
int t = 1;
for (int i = 0; i < 2; i++) {
double aspectRadius = Math.abs(Math.cos(asin) * currentRadius); //切线长度
float ax = (float) (aspectRadius * Math.cos(radians + asin * t));
float ay = (float) (aspectRadius * Math.sin(radians + asin * t));
if (fromCenter) {
canvas.drawLine(0, 0, ax, ay, paint);
} else {
canvas.drawLine(dx / 3, dy / 3, ax, ay, paint);
}
t = -1;
}
}
canvas.drawCircle(dx, dy, r, paint);
}
public void drawRect(Canvas canvas, Paint paint, long clockTime) {
long costTime = clockTime - startTime;
float dx = speedX * costTime;
float dy = speedY * costTime;
paint.setColor(color);
RectF rectF = new RectF(dx - r, dy - r, dx + r, dy + r);
canvas.drawRect(rectF, paint);
// canvas.drawCircle(dx,dy,r,paint);
}
}
}
四、总结
本篇我们大量使用了三角函数、反三角函数,因此一定要掌握好数学基础。