Android自定义View之音频条形图

新建项目,新建MusicRectangleView继承自View并重写onDrawonSizeChanged方法,onDraw方法用于绘制矩形onSizeChanged主要用于为矩形添加LinearGradient渐变,完整后新建变量如下:

private Paint mPaint;
    public int mOffset = 10;
    public int mRectWidth ;
    public int mRectHeight ;
    private int mRectCount = 10;
    private float currentHeight;
    private int mWidth;
    private LinearGradient mLinearGradient;

修改onDraw方法如下:

@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (int i=0;i<mRectCount;i++){
            currentHeight = (float)(Math.random()*mRectHeight);
            canvas.drawRect((float)(mWidth*0.4/2+mRectWidth*i+mOffset),currentHeight,(float)(mWidth*0.4/2+mRectWidth*(i+1)),mRectHeight,mPaint);
            postInvalidateDelayed(300);
        }
    }

修改onSizeChanged方法如下:

@Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mPaint = new Paint();
        mWidth = getWidth();
        mRectHeight = getHeight();
        mRectWidth = (int)(mWidth*0.6/mRectCount);
        mLinearGradient = new LinearGradient(0,0,mRectWidth,mRectHeight, Color.YELLOW,Color.BLUE, Shader.TileMode.CLAMP);
        mPaint.setShader(mLinearGradient);
    }

自此就完成了一个音频条形图的绘制,效果如下:

Android自定义View之音频条形图_第1张图片

源文件下载地址:源文件

你可能感兴趣的:(android)