前几天在网页上看到一个不错的加载动画View后,想将它在安卓上实现一遍。效果如下,很简单。
因为控件实现动画时,更新视图的频率会很高。为了减少内存的占用,决定使用SurfaceView来实现。
一、对控件的测量
使用的规则是:当控件的宽/高不是固定时,宽/高的大小为默认的宽高+padding值。反之,使用传递过来的宽高。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
if(modeWidth == MeasureSpec.AT_MOST || modeWidth == MeasureSpec.UNSPECIFIED ){
sizeWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,bwidth,getContext().getResources().getDisplayMetrics());
sizeWidth += getPaddingLeft()+getPaddingRight();
}
if(modeHeight == MeasureSpec.AT_MOST || modeHeight == MeasureSpec.UNSPECIFIED ){
sizeHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,bheight,getContext().getResources().getDisplayMetrics());
sizeHeight += getPaddingBottom()+getPaddingTop();
}
setMeasuredDimension(sizeWidth,sizeHeight);
}
二、对控件的绘制
private void drawView(Canvas canvas){
// 绘制背景图
canvas.drawColor(backgroundColor);
// 绘制电池框
canvas.drawRoundRect(SrectF,bRadius,bRadius,paintS);
// 绘制电池的小点
canvas.drawRect(centerX+bwidth/2-distance,centerY-bheight/4,centerX+bwidth/2,centerY+bheight/4,paintF);
// 更新电池填充的右边大小
FrectF.right = FrectF.left+varyInnerWidth;
// 绘制电池的填充
canvas.drawRoundRect(FrectF,bRadius,bRadius,paintF);
// 根据不同情况,修改电池填充的右边大小
if(SrectF.left+varyInnerWidth>centerX+bwidth