最近在做一个长按暂停的动画控件,实现的效果是这样:
这里实现的思想主要是利用 pathmesure 去不断截取矩形椭圆的长度,从而形成的动画效果:
核心代码如下:
protected void onDraw(Canvas canvas) {
mDst.reset();
mDst.lineTo(0, 0);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(mPauseBackgroudColor);
RectF bgRect = new RectF(mPadding * 2, mPadding * 2, mWidth - mPadding * 2, mHeight - mPadding * 2);
canvas.drawRoundRect(bgRect, mRadiusBg, mRadiusBg, mPaint);
int leftText = mWidth / 2;
Paint.FontMetricsInt fontMetrics = mPaintText.getFontMetricsInt();
float baseline = (bgRect.bottom + bgRect.top - fontMetrics.bottom - fontMetrics.top) / 2;
canvas.drawText(mPauseText, leftText, baseline, mPaintText);
if (MODE_OF_DRAW == DRAWING_MODE) {
RectF rect = new RectF(mPadding, mPadding, mWidth - mPadding, mHeight - mPadding);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(mStrokeWidth);
mPaint.setColor(PauseProgressSecondColor);
canvas.drawRoundRect(rect, mRadius, mRadius, mPaint);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(mStrokeWidth);
mPaint.setColor(mPauseProgressColor);
if (mAnimValue < 1.f) {
start = mLength * 0.25f;
stop = mLength * (mAnimValue);
mPathMeasure.getSegment(start, stop, mDst, true);
} else if (mAnimValue >= 1.f && mAnimValue <= 1.25f) {
mPathMeasure.getSegment(mLength * 0.25f, mLength, mDst, true);
canvas.drawPath(mDst, mPaint);
stop = mLength * (mAnimValue - 1);
start = 0;
mPathMeasure.getSegment(start, stop, mDst, true);
}
canvas.drawPath(mDst, mPaint);
} else if (MODE_OF_DRAW == CLEAR_MODE) {
mDst.reset();
mDst.lineTo(0, 0);
}
}
后面给出自定义类文件的下载,这里要注意的是截取矩形椭圆的起点位置默认是左边的半圆一半的位置,所以当我们改变起点的位置,就需要叠加两端来显示。
自定义属性如下:
<declare-styleable name="LongPressPauseView">
<attr name="PauseSpeed">
<enum name="low" value="1" />
<enum name="medium" value="2" />
<enum name="high" value="3" />
attr>
<attr name="PauseBackgroudColor" format="reference|color" />
<attr name="PauseProgressColor" format="reference|color" />
<attr name="PauseProgressSecondColor" format="reference|color" />
<attr name="PauseTextSize" format="reference|dimension" />
<attr name="PauseText" format="reference|string" />
declare-styleable>
在xml中的使用如下:
<com.yaoh.view.LongPressPauseView.LongPressPauseView
android:layout_width="300dp"
android:layout_height="80dp"
android:layout_centerInParent="true"
app:PauseBackgroudColor="@color/colorPrimary"
app:PauseProgressColor="@color/white_bg"
app:PauseProgressSecondColor="@color/gray_text_light"
app:PauseSpeed="medium"
app:PauseText="长按暂停"
app:PauseTextSize="18sp" />
还有地方需要完善,暂时就写到这里吧。