一個簡單的案例:可以看到音樂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);
}
}