项目中用到音乐播放,为了效果好看,自定义view来实现。先来看效果图
代码如下。初始化柱状图高度:
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
//初始化高度
mBottom = getMeasuredHeight() - getPaddingTop() -getPaddingBottom();
mLineFirstHeight =mBottom * 0.2f;
mLineSendHeight =mBottom *0.6f;
mLineThridHeight =mBottom *0.4f;
mLineForutHeight =mBottom * 0.8f;
//初始化宽度 4个指针
mLineWidth =(getMeasuredWidth() - getPaddingLeft() - getPaddingRight()) / 7;
}
得到高度后,开始绘制:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//绘制第一个 上升
canvas.drawRect(0, getUpHeight(mLineFirstHeight), mLineWidth, mBottom,mPaint);
//下降
canvas.drawRect(mLineWidth *2, getDownHeight(mLineSendHeight), mLineWidth *3, mBottom,mPaint);
//上升
canvas.drawRect(mLineWidth *4, getUpHeight(mLineThridHeight), mLineWidth *5, mBottom,mPaint);
//下降
canvas.drawRect(mLineWidth *6, getDownHeight(mLineForutHeight), mLineWidth *7, mBottom,mPaint);
}
接下来怎么让它动起来呢,使用属性动画:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
//获取高度 此处view已layout
mHeight = mSvPlay.getHeight();
}
//执行动画
private void statAnim() {
//执行动画
mTranslationY = ObjectAnimator.ofFloat(mSvPlay, "transY", 0, mHeight * 2);
mTranslationY.setDuration(2000);
mTranslationY.setRepeatMode(ValueAnimator.RESTART);
mTranslationY.setRepeatCount(ValueAnimator.INFINITE);
mTranslationY.setInterpolator(new LinearInterpolator());
mTranslationY.start();
}
在自定义view中计算高度:
/**
* 获取刚开始上升的高的度
* @param nowHeight 初始化的高度
* @return 新的高度
*/
private float getUpHeight(float nowHeight){
if(Math.abs(nowHeight - transY) > mBottom){
return mBottom * 2 - (transY - nowHeight);
}else{
return Math.abs(nowHeight - transY);
}
}
/**
* 获取刚开始下降的高的度
* @param nowHeight 初始化的高度
* @return 新的高度
*/
private float getDownHeight(float nowHeight){
if(nowHeight + transY > mBottom){
return Math.abs(mBottom * 2 -(nowHeight + transY));
}else{
return nowHeight + transY;
}
}
这样就可以了,特别简单吧。至于怎么停止可以使用
mTranslationY.cancel();
来结束动画;
因为项目中就一个地方使用,所以未自定义属性,有需要的朋友可做适配。GitHub直达车