示波器是在大学的时候老师教的,但是出来工作一直没有用到过,渐渐的也就忘记了,现在重新学习一下。来看看效果图:
这里是一个自定义的柱状图,然后有一个按钮,点击按钮的时候,这里柱子会不停的运动,类似于音乐播放器里示波器的跳动。
跟前面几个自定义view的方式类似,重写了onSizeChange()方法和onDraw()方法
先列一下我们要用到的变量:
/**画笔*/
private Paint mPaint;
/**控件的宽度*/
private float mWidth;
/**单个柱子的宽度*/
private float mRectWidth;
/**单个柱子的高度*/
private float mRectHeight;
/**柱子的总个数*/
private float mRectCount = 10;
/**柱子之间的间隔*/
private int offsets = 2;
/**Android中的线性渐变*/
private LinearGradient mLinearGradient;
/**随机的柱子的高度*/
private double mRandom;
所有的变量都在这里了
下面给画笔初始化
/**
* 初始化画笔
*/
private void initView() {
mPaint = new Paint();
mPaint.setAntiAlias(true);
}
然后在onSizeChange()里面给变量赋值
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
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);
}
最后绘制柱状图
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i = 0; i < mRectCount; i++) {
mRandom = Math.random();
float currentHeight = (float) (mRectHeight * mRandom);
canvas.drawRect(
(float) (mWidth * 0.4 / 2 + mRectWidth * i + offsets),
currentHeight, (float) (mWidth * 0.4 / 2 + mRectWidth
* (i + 1)), mRectHeight, mPaint);
}
}
这个时候,一个音乐播放器的示波器已经完成了,但是,这个是静态的,接下来,向外面暴露一个方法,用于刷新View,实现动态的效果。
public void onStart() {
postInvalidateDelayed(300);
}
每间隔300ms对View进行重绘,就可以有一个比较好的视觉效果了。
好了,最后我贴上全部的代码:
public class MusicLine extends View {
private Paint mPaint;
private float mWidth;
private float mRectWidth;
private float mRectHeight;
private float mRectCount = 10;
private int offsets = 2;
private LinearGradient mLinearGradient;
private double mRandom;
public MusicLine(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView();
}
public MusicLine(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public MusicLine(Context context) {
super(context);
initView();
}
/**
* 初始化工具类
*/
private void initView() {
mPaint = new Paint();
mPaint.setAntiAlias(true);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
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);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i = 0; i < mRectCount; i++) {
mRandom = Math.random();
float currentHeight = (float) (mRectHeight * mRandom);
canvas.drawRect(
(float) (mWidth * 0.4 / 2 + mRectWidth * i + offsets),
currentHeight, (float) (mWidth * 0.4 / 2 + mRectWidth
* (i + 1)), mRectHeight, mPaint);
}
}
public void onStart() {
postInvalidateDelayed(300);
}
}
至此,全部完成了。