分类:
Android(26)
版权声明:本文为博主原创文章,未经博主允许不得转载。
新建项目,新建MusicRectangleView
继承自View
并重写onDraw
和onSizeChanged
方法,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;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
修改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);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
修改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);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
自此就完成了一个音频条形图的绘制,效果如下:
源文件下载地址:源文件