温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Android中自定义一个音乐波动特效图

发布时间:2021-04-30 15:30:50 来源:亿速云 阅读:312 作者:Leah 栏目:开发技术

今天就跟大家聊聊有关如何在Android中自定义一个音乐波动特效图,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

Android是什么

Android是一种基于Linux内核的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由美国Google公司和开放手机联盟领导及开发。

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

看完上述内容,你们对如何在Android中自定义一个音乐波动特效图有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI