根据上一篇PathMeasure的介绍,我们来实现一个好看的 加载效果
直接贴代码
public class PathMeasureView extends View
{
private Paint mPaint = new Paint();
private Paint mLinePaint = new Paint(); //坐标系
private Bitmap mBitmap;
private int width, height;
private float len;
private float mInnerLenght;
private boolean isor = false;
Path dst = new Path();
Path innerDst = new Path();
public PathMeasureView(Context context)
{
this(context, null);
}
public PathMeasureView(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public PathMeasureView(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.BLACK);
mPaint.setStrokeWidth(4);
mLinePaint.setStyle(Paint.Style.STROKE);
mLinePaint.setColor(Color.RED);
mLinePaint.setStrokeWidth(6);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width = MeasureSpec.getSize(widthMeasureSpec);
height = MeasureSpec.getSize(heightMeasureSpec);
//防止过度测量
if(!isor)
{
isor=true;
Path path = new Path();
path.addCircle(width/2, height/2, 50, Path.Direction.CW);
path.addCircle(width/2, height/2, 50, Path.Direction.CCW);
final PathMeasure pathMeasure = new PathMeasure(path, false);
len = pathMeasure.getLength();
final PathMeasure pathMeasure1 = new PathMeasure(path, false);
//移动到下一个path曲线
pathMeasure1.nextContour();
mInnerLenght=pathMeasure1.getLength();
ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
animator.setDuration(1500);
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.setInterpolator(new LinearInterpolator());
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
{
@Override
public void onAnimationUpdate(ValueAnimator animation)
{
dst.reset();
innerDst.reset();
float start = (float) ((len * (float) animation.getAnimatedValue()) - ((0.5 - Math.abs((float) animation.getAnimatedValue() - 0.5)) * len));
pathMeasure.getSegment(start, (len * (float) animation.getAnimatedValue()), dst, true);
//pathMeasure.getSegment(0, (len * (float) animation.getAnimatedValue()), dst, true);
float start1 = (float) ((mInnerLenght * (float) animation.getAnimatedValue()) - ((0.5 - Math.abs((float) animation.getAnimatedValue() - 0.5)) * mInnerLenght));
pathMeasure1.getSegment(start1, (mInnerLenght * (float) animation.getAnimatedValue()), innerDst, true);
invalidate();
}
});
animator.start();
}
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawPath(dst, mLinePaint);
canvas.drawPath(innerDst, mLinePaint);
}
private float[] pos = new float[2];
private float[] tan = new float[2];
}