欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android简单自定义音乐波动特效图

程序员文章站 2022-04-23 19:02:07
本文实例为大家分享了android简单自定义音乐波动特效图的具体代码,供大家参考,具体内容如下最终效果:思路:就是绘制一个不断变化高度的矩形或者是宽虚线1.自定义属性:

本文实例为大家分享了android简单自定义音乐波动特效图的具体代码,供大家参考,具体内容如下

最终效果:

Android简单自定义音乐波动特效图

思路:就是绘制一个不断变化高度的矩形或者是宽虚线

1.自定义属性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="musicplayviewattr">
        <!--指针颜色-->
        <attr name="point_color" format="color" />
        <!--指针数量-->
        <attr name="point_num" format="integer" />
        <!--指针宽度-->
        <attr name="point_width" format="float" />
        <!--指针波动速度-->
        <attr name="point_speed" format="integer" />
    </declare-styleable>
</resources>

2.编写自定义musicplayview

/**
 * 音乐播放波动动画
 */
 
public class musicplayview extends view {
    //坐标原点x
    private float mbasepointx;
 
    //坐标原点y
    private float mbasepointy;
 
    //指针的数量 默认10
    private int mpointnum;
 
    //指针间的间隙  默认5dp
    private float mpointspace;
 
    //每个指针的宽度 默认5dp
    private float mpointwidth;
 
    //指针的颜色
    private int mpointcolor = color.red;
 
    //指针的集合
    private list<pointer> mpoints;
 
    //控制开始/停止
    private boolean misplaying = false;
 
    //播放线程
    private thread mplaythread;
 
    //指针波动速度
    private int mpointspeed;
 
    //画笔
    private paint mpaint;
 
    public musicplayview(context context) {
        super(context);
        init();
    }
 
    public musicplayview(context context, @nullable attributeset attrs) {
        super(context, attrs);
        //取出自定义属性
        typedarray ta = context.obtainstyledattributes(attrs, r.styleable.musicplayviewattr);
        mpointnum = ta.getint(r.styleable.musicplayviewattr_point_num, 10);
        mpointwidth = dp2px(getcontext(),
                ta.getfloat(r.styleable.musicplayviewattr_point_width, 5f));
        mpointcolor = ta.getcolor(r.styleable.musicplayviewattr_point_color, color.red);
        mpointspeed = ta.getint(r.styleable.musicplayviewattr_point_speed, 40);
        init();
    }
 
    public musicplayview(context context, @nullable attributeset attrs, int defstyleattr) {
        super(context, attrs, defstyleattr);
        typedarray ta = context.obtainstyledattributes(attrs, r.styleable.musicplayviewattr);
        mpointnum = ta.getint(r.styleable.musicplayviewattr_point_num, 10);
        mpointwidth = dp2px(getcontext(), ta.getfloat(r.styleable.musicplayviewattr_point_width, 5f));
        mpointcolor = ta.getcolor(r.styleable.musicplayviewattr_point_color, color.red);
        mpointspeed = ta.getint(r.styleable.musicplayviewattr_point_speed, 40);
        init();
    }
 
    /**
     * 初始化画笔
     */
    private void init() {
        mpoints = new arraylist<>();
        //绘制虚线
        mpaint = new paint(paint.anti_alias_flag);
        mpaint.setcolor(mpointcolor);
        mpaint.setantialias(true);
        mpaint.setstrokewidth(mpointwidth);
        mpaint.setpatheffect(new dashpatheffect(new float[]{25, 15}, 0));//虚线间隔
        setlayertype(layer_type_software, null);
    }
 
    /**
     * 设置指针高度和即那个
     */
    @override
    protected void onlayout(boolean changed, int left, int top, int right, int bottom) {
        super.onlayout(changed, left, top, right, bottom);
        //获取逻辑原点的y
        mbasepointy = getheight() - getpaddingbottom();
        random random = new random();
        if (mpoints != null)
            mpoints.clear();
        for (int i = 0; i < mpointnum; i++) {
            //随机高度
            mpoints.add(new pointer((float) (0.1 * (random.nextint(10) + 1) * (getheight() - getpaddingbottom() - getpaddingtop()))));
        }
        //计算每个指针之间的间隔  view宽度 - 左右的padding - 所有指针总共宽度   再除以多少个间隔
        mpointspace = (getwidth() - getpaddingleft() - getpaddingright() - mpointwidth * mpointnum) / (mpointnum - 1);
 
    }
 
 
    /**
     * 开始绘制虚线
     */
    @override
    protected void ondraw(canvas canvas) {
        super.ondraw(canvas);
        //指针x位置
        mbasepointx = 0f + getpaddingleft() + mpointwidth / 2;
        //绘制每一个指针。
        for (int i = 0; i < mpoints.size(); i++) {
            //绘制虚线
            float[] pts = {mbasepointx, getheight(), mbasepointx, (mbasepointy - mpoints.get(i).getheight())};//重下往上动画
            canvas.drawlines(pts, mpaint);
            //更新指针x位置
            mbasepointx += (mpointspace + mpointwidth);
        }
    }
 
    /**
     * 开始线程 播放
     */
    public void start() {
        setvisibility(visible);
        if (!misplaying) {
            if (mplaythread == null) {
                mplaythread = new thread(new playrunnable());
                mplaythread.start();
            }
            misplaying = true;//控制子线程中的循环
        }
    }
 
    /**
     * 停止线程 停止播放
     */
    public void stop() {
        setvisibility(invisible);
        misplaying = false;
        invalidate();
    }
 
    /**
     * 更新ui
     */
    private handler myhandler = new handler() {
        @override
        public void handlemessage(message msg) {
            super.handlemessage(msg);
            invalidate();
        }
    };
 
    /**
     * 子线程,循环改变每个指针的高度
     */
    public class playrunnable implements runnable {
 
        @override
        public void run() {
            for (float i = 0; i < integer.max_value; ) {
                try {
                    for (int j = 0; j < mpoints.size(); j++) {
                        float rate = (float) math.abs(math.sin(i + j));//随机数
                        mpoints.get(j).setheight((mbasepointy - getpaddingtop()) * rate); //每个指针的高度
                    }
                    thread.sleep(mpointspeed);//控制动画速度
                    //开始/暂停
                    if (misplaying) {
                        myhandler.sendemptymessage(0);
                        i += 0.1;
                    }
                } catch (interruptedexception e) {
                    e.printstacktrace();
                }
            }
        }
    }
 
    /**
     * 指针对象
     */
    public class pointer {
        private float height;
 
        public pointer(float height) {
            this.height = height;
        }
 
        public float getheight() {
            return height;
        }
 
        public void setheight(float height) {
            this.height = height;
        }
    }
 
    /**
     * dp转px
     */
    public static int dp2px(context context, float dpval) {
        return (int) typedvalue.applydimension(typedvalue.complex_unit_dip, dpval, context.getresources()
                .getdisplaymetrics());
    }
}

3.在activity_main2布局中使用musicplayview

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".mainactivity">
 
    <com.hk.testapplication.musicplayview
        android:id="@+id/music_play"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:visibility="invisible"
        android:padding="10dp"
        app:point_color="#f44336"
        app:point_num="10"
        app:point_width="14" />
    <linearlayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <button
            android:id="@+id/bt_play"
            android:layout_marginleft="20dp"
            android:layout_marginright="20dp"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="播放"/>
        <button
            android:id="@+id/bt_stop"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:layout_marginleft="20dp"
            android:layout_marginright="20dp"
            android:text="停止"/>
 
    </linearlayout>
 
</linearlayout>

4.mainactivity中使用

public class mainactivity2 extends appcompatactivity implements view.onclicklistener {
    private button mbtplay,mbtstop;
    private musicplayview mmusicplayview;
    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_main2);
        mmusicplayview = findviewbyid(r.id.music_play);
        mbtplay = findviewbyid(r.id.bt_play);
        mbtstop = findviewbyid(r.id.bt_stop);
        mbtplay.setonclicklistener(this);
        mbtstop.setonclicklistener(this);
    }
    @override
    public void onclick(view v) {
        switch (v.getid()){
            case r.id.bt_play:
                //开始播放
                mmusicplayview.start();
                break;
            case r.id.bt_stop:
                //停止播放
                mmusicplayview.stop();
                break;
 
        }
    }
}

因为注释都挺详细的,就没有做太多的介绍,我这里也只是提供一个思路,里面有很多可以优化的地方比方说线程使用和循环的时候,如果有不懂的地方可以留言。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。