自定义View,模仿音乐播放器音频条形图

这次写到的是自定义view的实现音乐滚动音频条的过程,笔者在这里有两点启发,记下来,以便以后复习。
其中用到了postInvalidateDelayed(long mil)方法来刷新view视图,其底层用的是handler机制,handler机制不在此次练习范围之内,不再赘述。
主要代码如下:

    private float offset = 5;//矩形条之间的间距
    private float width ;//矩形条的宽度
    private float baseheight;//此View的高度
    private float height ;//每个矩形条的高度(随机获取,每次不一样)
    private int rectSize = 10;//矩形条的数量

    private Paint mpaint;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        for (int i=0 ; i <rectSize  ; i++){

            //每次绘制前随机计算一个矩形条的高度
            double random = Math.random();
            height = (float)(baseheight*random);


            canvas.drawRect((width +offset)*i,
                    height,
                    (width+offset)*i+width,
                    baseheight,mpaint);
        }

        //刷新view,每300毫秒执行一次ondraw()
        postInvalidateDelayed(300);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        //再次方法中初始化一些变量,次方发在View测量大小后执行
        baseheight  = getMeasuredHeight();
        width = (getMeasuredWidth()- offset*9)/rectSize ;
        initPaint();
    }

    public void initPaint(){
        mpaint = new Paint();
        mpaint.setColor(Color.BLUE);
        mpaint.setStyle(Paint.Style.FILL);
    }

布局中引用:

<com.demo.alldemos.diyviews.MusicView
        android:layout_width="200dp"
        android:layout_height="200dp" />

代码中把矩形条儿的数目定死为10,如有需要,可自定义属性更改之。

发布了17 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_24295537/article/details/50912493