Android 绘制变化的音频

时间:2021-07-06 00:04:39

通过自定义view来绘制一个不断变化的音频条形图

public class SoundWave extends View {
private int mWidth, mHeight;
// 默认矩形数量
private int mRectCount = 10;

private Paint paintRect;

public SoundWave(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

public SoundWave(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}

public SoundWave(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);

if (widthMode == MeasureSpec.EXACTLY) {
mWidth = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
throw new IllegalArgumentException(
"width must be EXACTLY,you should set like android:width=\"200dp\"");
}

if (heightMode == MeasureSpec.EXACTLY) {
mHeight = heightSize;
} else if (widthMeasureSpec == MeasureSpec.AT_MOST) {

throw new IllegalArgumentException(
"height must be EXACTLY,you should set like android:height=\"200dp\"");
}

setMeasuredDimension(mWidth, mHeight);
}

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

// view区域左右各留白1/5
int mRectWidth = (int) (mWidth * 0.6 / mRectCount);
int mRectHeight = mHeight - 20;
for (int i = 0; i < mRectCount; i++) {
// 随机产生矩形高度
double mRandom = Math.random();
float currentHeight = (float) (mHeight * mRandom);
canvas.drawRect((float) (mWidth * 0.4 / 2 + mRectWidth * i),
currentHeight, (float) (mWidth * 0.4 / 2 + mRectWidth
* (i + 1)), mRectHeight, paintRect);
}
// 延迟0.3秒刷新一次
postInvalidateDelayed(300);
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// 初始化先调用onSizeChanged
int mRectWidth = (int) (mWidth * 0.6 / mRectCount);
int mRectHeight = mHeight - 20;
// 设置线性渐变
LinearGradient mLinearGradient = new LinearGradient(0, 0, mRectWidth,
mRectHeight, Color.YELLOW, Color.BLUE, Shader.TileMode.CLAMP);
paintRect = new Paint();
paintRect.setStyle(Paint.Style.FILL);
paintRect.setShader(mLinearGradient);
}
}