基于Android实现烟花效果

 更新时间:2023年11月21日 08:54:55   作者:时光少年  
这篇文章文章我们将介绍如何通过Canvas 2D坐标系实现粒子效果,文中通过代码示例和图文结合介绍的非常详细,对大家的学习或工作有一定的帮助,感兴趣的同学可以自己动手尝试一下

一、效果预览

无中心版本

有中心版本

二、实现

2.1 均匀分布

我们首要解决的问题是计算出粒子运动方向,保证粒子能正常扩散到目标范围和区域,另外还有保证粒子尽可能随机和均匀分布在任意方向。

方法是:

粒子扩散的范围是一个圆的范围内,我们要尽可能利用圆的旋转半径和夹角之间的关系,属于高中数学知识。另外也要控制粒子的数量,防止堆叠过多的问题。

int t = i % 12;  
double degree = random.nextFloat() * 30 + t * 30;  // 12等分圆,没等分都保证产生粒子 
// 360 /12 = 30 ,意味着每等分30度区域内需要产生一定的粒子

2.2 速度计算

我们上一篇说过,计算出速度是最难的,要结合场景,这里我们采样计算终点的方式,目的有2个,限制粒子运动出大圆,限制时间。

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 颜色

颜色选择自己喜欢的就可以,我喜欢五彩缤纷,所以随机生成

int color = argb(random.nextFloat(), random.nextFloat(), random.nextFloat());

2.4 定义粒子对象

    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 基础骨架

        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 进一步优化

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闭合,但是计算量和难度太大了,直接使用贝塞尔曲线更省事。

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

        }
    }

}

四、总结

本篇我们大量使用了三角函数、反三角函数,因此一定要掌握好数学基础。

以上就是基于Android实现烟花效果的详细内容,更多关于Android烟花效果的资料请关注脚本之家其它相关文章!

相关文章

  • 详解Android登陆界面用户协议解决方案

    详解Android登陆界面用户协议解决方案

    这篇文章主要介绍了详解Android登陆界面用户协议解决方案,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-08-08
  • Android 中CheckBox多项选择当前的position信息提交的示例代码

    Android 中CheckBox多项选择当前的position信息提交的示例代码

    这篇文章主要介绍了Android 中CheckBox多项选择当前的position信息提交的示例代码,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2017-07-07
  • Android通过startService实现文件批量下载

    Android通过startService实现文件批量下载

    这篇文章主要为大家详细介绍了Android通过startService实现文件批量下载的示例,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2015-12-12
  • Android使用fastjson库解析json字符串实战

    Android使用fastjson库解析json字符串实战

    fastjson是一个Java语言编写的高性能功能完善的JSON库,它采用一种“假定有序快速匹配”的算法,把JSON Parse的性能提升到极致,是目前Java语言中最快的JSON库,Fastjson接口简单易用,已经被广泛使用在缓存序列化、协议交互、Web输出、Android客户端等多种应用场景
    2023-11-11
  • Android多边形区域扫描线种子填充算法的示例

    Android多边形区域扫描线种子填充算法的示例

    这篇文章主要介绍了Android多边形区域扫描线种子填充算法的示例,具有很好的参考价值,希望对大家有所帮助,一起跟随小编过来看看吧
    2018-05-05
  • Android自定义View实现多边形统计图示例代码

    Android自定义View实现多边形统计图示例代码

    这篇文章主要给大家介绍了关于Android自定义View如何实现多边形统计图的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
    2018-01-01
  • OpenGL Shader实现物件材料效果详解

    OpenGL Shader实现物件材料效果详解

    在一些主流app上有一些比较特殊的滤镜效果,例如灰尘、塑料封面、光影效果等,这些其实是纹理叠加的效果。本文将用OpenGL Shader实现这些效果,需要的可以参考一下
    2022-02-02
  • Android实现简单旋转动画

    Android实现简单旋转动画

    这篇文章主要为大家详细介绍了Android实现简单旋转动画,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-07-07
  • android 拍照和上传的实现代码

    android 拍照和上传的实现代码

    怎么把拍照好的图片数据放到gallery中显示又要保存到sdcard上,请看下面的实例
    2013-09-09
  • Android集成Flutter

    Android集成Flutter

    本文主要从一个 Android 开发的视角,谈谈 Android 平台下, Flutter 的混合开发与构建,如果你也感兴趣的话一起参与学习吧
    2021-08-08

最新评论