标签:android
下面来实现一个loading效果。具体效果如下:
首先对这个效果进行拆分,它由以下部分组成:
拆分完效果后,思考下如何实现。下面是我的思考过程。
大致思考完之后,可以写代码了。
首先是measure过程:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//需要计算自己实际需要的宽高
//需要把padding考虑进来
//需要考虑父容器的测量规则
int width,height;
width = (int)mViewMinWidth+getPaddingLeft()+getPaddingRight();
height = (int)mViewMinHeight+getPaddingTop()+getPaddingBottom();
setMeasuredDimension(getMeasuredSize(widthMeasureSpec, width), getMeasuredSize(heightMeasureSpec, height));
}
通过getMeasuredSize计算考虑父容器限制后的实际大小:
private int getMeasuredSize(int measureSpec,int desiredSize){
int result;
int mode = MeasureSpec.getMode(measureSpec);
int size = MeasureSpec.getSize(measureSpec);
switch (mode){
case MeasureSpec.EXACTLY:
result = size;
break;
default:
result = desiredSize;
if(mode == MeasureSpec.AT_MOST)
result = Math.min(result,size);
break;
}
return result;
}
然后是draw的过程:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.setColor(mViewBackground);
//如果xml中设置layout_width/layout_height大于默认宽高,那么居中(不允许小于默认宽高)
if(getWidth()-getPaddingLeft()-getPaddingRight() > (int)mViewMinWidth || getHeight()-getPaddingTop()-getPaddingBottom() > (int)mViewMinHeight){
canvas.translate((getWidth()-mViewMinWidth)/2.0f,(getHeight()-mViewMinHeight)/2.0f);
}
//画圆角矩形
canvas.drawRoundRect(mBounds, dp2px(5), dp2px(5), mPaint);
//平移到圆角矩形中心点,画闪电
canvas.translate((mViewMinWidth - mDefaultWidth) / 2.0f, (mViewMinHeight - mDefaultHeight) / 2.0f);
mPaint.setColor(mBackgroundColor);
canvas.drawPath(mThunderPath, mPaint);
mPaint.setColor(mCoverColor);
//通过clicpRect的方式控制可绘制区域(在外界看来好像有闪动的动画效果)
canvas.clipRect(getPaddingLeft(), mScanTop + getPaddingTop(), mDefaultWidth + getPaddingLeft(), mScanBottom + getPaddingTop());
canvas.drawPath(mThunderPath, mPaint);
}
mScanTop/mScanBottom变量可以通过post()进行改变:
class AnimRunnable implements Runnable{
@Override
public void run() {
if (!flag) {
mScanBottom += mGap;
if (mScanBottom >= mDefaultHeight) {
mScanBottom = (int) mDefaultHeight;
flag = true;
}
postInvalidate();
post(this);
} else {
mScanTop += mGap;
if (mScanTop >= mDefaultHeight) {
mScanTop = mScanBottom = 0;
flag = false;
postInvalidate();
postDelayed(this, 700);
} else {
postInvalidate();
post(this);
}
}
}
}
private void startAnim() {
mRunnable = new AnimRunnable();
post(mRunnable);
}
核心代码就这么多。
完整代码在这里:https://github.com/Rowandjj/ThunderLoadingView
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:android
原文地址:http://blog.csdn.net/chdjj/article/details/47304323