2016-04-12 17:52 76人阅读 评论(2)  举报
Android自定义View之音频条形图-LMLPHP 分类:
Android(26) Android自定义View之音频条形图-LMLPHP

版权声明:本文为博主原创文章,未经博主允许不得转载。

新建项目,新建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;
  • 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

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

Android自定义View之音频条形图-LMLPHP

源文件下载地址:源文件

 
 
05-11 11:35