一个简单的案例:可以看到音乐app上有些音频条,随着音调的大小条形图也发生变化,在这里不去真实地监听音频输入了,只是用一些数字来模拟即可。
条形图不断变化。
public class VoiceView extends View {
private static final String TAG = "VoiceView";
/**
* 小矩形的总数
*/
private int mRectCount;
private int mWidth;
/**
* 小矩形的宽度
*/
private int mRectWidth;
/**
* 小矩形底部所在的高度
*/
private int mRectHeight;
private float mRandom;
/**
* 两个小矩形之间的间距
*/
private int offset;
private Paint mPaint;
/**
* 小矩形的着色器
*/
private LinearGradient mLinearGradient;
public VoiceView(Context context) {
this(context, null);
}
public VoiceView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public VoiceView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initData();
}
private void initData() {
mRectCount = 10;
offset = 5;
mPaint = new Paint();
mPaint.setColor(Color.GRAY);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = getWidth();
mRectHeight = getHeight()/2;
mRectWidth = (int) (mWidth*0.6/mRectCount);
mLinearGradient = new LinearGradient(0, 0, mRectWidth, mRectHeight, Color.YELLOW, Color.BLUE, Shader.TileMode.CLAMP);
mPaint.setShader(mLinearGradient);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
/**
* 小矩形的高
*/
for (int i=0; i<mRectCount; i++){
mRandom = (float) Math.random();
/**
* 矩形的高度,这里使用的是随机数
*/
float currentHeight = mRectHeight*mRandom;
canvas.drawRect((float) (mWidth*0.4/2+mRectWidth*i+offset),
currentHeight,
(float) (mWidth*0.4/2+mRectWidth*(i+1)),
mRectHeight,
mPaint
);
}
postInvalidateDelayed(300);
}
}