一個絢麗的downloading動效分析與實現!

閒逛之餘,看到一個不錯的downloading動效,這個動效用CJJ的話說難度還好,但本人以爲還比較靈動、帶感、俏皮、有新意,好了話很少說,我們先來擼一張高清無碼gif圖: javascript

擼完,咱能夠將整個動效簡單劃分爲如下流程:
1.BeforeProgress(顯示進度前);
2.InProgress(顯示進度中);
3.Failed(失敗動畫);
4.Done(完成動畫);java

下面我們一塊兒對以上流程進行分析與實現;git


1.BeforeProgress(顯示進度前):github

一樣,我們一塊兒擼一下第一部分高清無碼gif圖:
canvas


經過觀察,咱們能夠將以上動畫分割爲如下幾個內容:
1.圓形背景和下載剪頭總體縮放;
2.圓形背景逐步鏤空(縮放到必定階段,內部鏤空圓不斷擴大);
3.圓形背景變爲一條直線,並伴隨箭頭些許上移;
4.直線上下震盪及下載箭頭(Arrow)變承載進度文字的線框形態;

1.1. 圓形背景和下載剪頭總體縮放:函數

這裏面,圓形背景和總體的縮放好說,稍顯麻煩的是下載箭頭,因爲後面箭頭還須要形變爲承載進度文字的線框,因此丟掉你使用圖片的小想法,我們一塊兒用path勾一個活潑的小箭頭:post

// move to bottom center
mArrowPath.moveTo(halfArrowWidth, 0);
// rect bottom left edge
mArrowPath.lineTo(rectPaddingLeft, 0);
// rect left edge
mArrowPath.lineTo(rectPaddingLeft, rectHeight);
// tri bottom left edge
mArrowPath.lineTo(triPaddingLeft, rectHeight);
// tri left edge
mArrowPath.lineTo(halfArrowWidth, arrowHeight);
// tri right edge
mArrowPath.lineTo(arrowWidth - triPaddingLeft, rectHeight);
// tri bottom right edge
mArrowPath.lineTo(arrowWidth - rectPaddingLeft, rectHeight);
// rect right edge
mArrowPath.lineTo(arrowWidth - rectPaddingLeft, 0);
// rect right bottom edge
mArrowPath.lineTo(halfArrowWidth, 0);複製代碼

箭頭OK了,圓形背景和總體的縮放就再也不細說,只須要canvas.drawCircle()和使用ValueAnimator動態改變canvas縮放比例便可,so easy!動畫

後面箭頭須要形變爲承載進度文字的線框,經過觀察,能夠看到線框的4個角是圓角。因爲使用path勾勒,實現圓角線框大體有如下幾種方案:ui

1.使用path的quadTo()以二次貝塞爾曲線鏈接;
2.使用path的arcTo()以圓弧形式鏈接;
3.使用path中addArc()添加一段圓;
4.使用paint的setPathEffect設置PathEffect爲ConnerPathEffect;spa

本人最終採用第四種方式進行實現;

1.2.圓形背景逐步鏤空(縮放到必定階段,內部鏤空圓不斷擴大):


擼完上圖,咱們可看到,圓形背景由實心圓變換至一個圓環,最終消失,此處咱們能夠想到以下方案:

1.直接採用背景的顏色,在裏面畫實心圓(須要提早知道背景顏色而且背景只能爲純色);
2.外面深色的圓直接是圓環,而後經過調整圓的半徑及paint的strokeWidth實現;
3.直接採用混合模式(Xfermode),圓形背景中混合掉內圓部分;

第一種方案太挫,帥氣逼人的GAStudio哥確定不會考慮,本文采用混合模式方案,關鍵代碼以下:

int layoutCont = canvas.saveLayer(mCircleRectF, mDefaultPaint, Canvas.ALL_SAVE_FLAG);
mDefaultPaint.setColor(mLoadingCircleBackColor);
canvas.drawCircle(mCircleRectF.centerX(), mCircleRectF.centerY(), mCircleRadius, mDefaultPaint);

mDefaultPaint.setXfermode(mXfermode);
// draw bg circle 2
int innerCircleRadius = (int) (mCircleRadius * innerCircleScalingFactor);
canvas.drawCircle(mCircleRectF.centerX(), mCircleRectF.centerY(), innerCircleRadius, mDefaultPaint);
mDefaultPaint.setXfermode(null);
canvas.restoreToCount(layoutCont);複製代碼

1.3.圓形背景變爲一條直線,並伴隨箭頭些許上移:


這個部分相比前面兩步稍顯複雜,須要將圓環如絲般順滑的變換成直線,並隨之上線震盪,該過程拆解圖以下:

對於這個過程,GAStudio哥採用兩條三階貝塞爾曲線對初期的圓環、中間部分的曲線、最終的直線進行模擬;

爲了便於理解,抽象出四個核心狀態,過程圖解以下:

1.完整圓形狀態:


2.延展開來狀態:

3.橫向鋪開狀態:

4.直線狀態:

更新path核心邏輯以下:

private void updateCircleToLinePath(Path linePath, int circleDiameter, float normalizedTime) {
    if (linePath == null) {
        return;
    }
    int index = 0;
    float adjustNormalizedTime = 0;
    if (normalizedTime <= CIRCLE_TO_LINE_SEASONS[1]) {
        adjustNormalizedTime = normalizedTime / CIRCLE_TO_LINE_SEASONS[1];
    } else if (normalizedTime < CIRCLE_TO_LINE_SEASONS[2]) {
        index = 1;
        adjustNormalizedTime = (normalizedTime - CIRCLE_TO_LINE_SEASONS[1])
                / (CIRCLE_TO_LINE_SEASONS[2] - CIRCLE_TO_LINE_SEASONS[1]);
    } else {
        index = 2;
        adjustNormalizedTime = (normalizedTime - CIRCLE_TO_LINE_SEASONS[2])
                / (CIRCLE_TO_LINE_SEASONS[3] - CIRCLE_TO_LINE_SEASONS[2]);
    }

    // the path bounds width
    int boundWidth = (int) (((CIRCLE_TO_LINE_WIDTH_FACTOR[index + 1]
            - CIRCLE_TO_LINE_WIDTH_FACTOR[index])
            * adjustNormalizedTime + CIRCLE_TO_LINE_WIDTH_FACTOR[index]) * circleDiameter);

    // the distance of cubic line1' x1 to cubic line2's x2
    int adjustBoundWidth = boundWidth;
    if (normalizedTime <= CIRCLE_TO_LINE_SEASONS[1]) {
        adjustBoundWidth = (int) (boundWidth * adjustNormalizedTime);
    }

    // the path bounds height
    int boundHeight = (int) (((CIRCLE_TO_LINE_HEIGHT_FACTOR[index + 1]
            - CIRCLE_TO_LINE_HEIGHT_FACTOR[index])
            * adjustNormalizedTime + CIRCLE_TO_LINE_HEIGHT_FACTOR[index]) * circleDiameter);

    // calculate the four points
    float firstControlXFactor = (CIRCLE_TO_LINE_FST_CON_X_FACTOR[index + 1]
            - CIRCLE_TO_LINE_FST_CON_X_FACTOR[index])
            * adjustNormalizedTime + CIRCLE_TO_LINE_FST_CON_X_FACTOR[index];
    float firstControlYFactor = (CIRCLE_TO_LINE_FST_CON_Y_FACTOR[index + 1]
            - CIRCLE_TO_LINE_FST_CON_Y_FACTOR[index])
            * adjustNormalizedTime + CIRCLE_TO_LINE_FST_CON_Y_FACTOR[index];
    float secondControlXFactor = (CIRCLE_TO_LINE_SEC_CON_X_FACTOR[index + 1]
            - CIRCLE_TO_LINE_SEC_CON_X_FACTOR[index])
            * adjustNormalizedTime + CIRCLE_TO_LINE_SEC_CON_X_FACTOR[index];
    float secondControlYFactor = (CIRCLE_TO_LINE_SEC_CON_Y_FACTOR[index + 1]
            - CIRCLE_TO_LINE_SEC_CON_Y_FACTOR[index])
            * adjustNormalizedTime + CIRCLE_TO_LINE_SEC_CON_Y_FACTOR[index];
    int firstControlX = (int) (circleDiameter * firstControlXFactor);
    int firstControlY = (int) (circleDiameter * firstControlYFactor);
    int secondControlX = (int) (circleDiameter * secondControlXFactor);
    int secondControlY = (int) (circleDiameter * secondControlYFactor);

    linePath.reset();
    // left line
    linePath.cubicTo(firstControlX, firstControlY,
            secondControlX, secondControlY, adjustBoundWidth / 2, boundHeight);
    // left right line
    linePath.cubicTo(adjustBoundWidth - secondControlX,
            secondControlY, adjustBoundWidth - firstControlX, firstControlY, adjustBoundWidth, 0);

    // translate path to move the origin to the center
    int offsetX = (circleDiameter - adjustBoundWidth) / 2;
    int offsetY = (circleDiameter - boundHeight) / 2;
    linePath.addCircle(firstControlX, firstControlY,3, Path.Direction.CW);
    linePath.addCircle(secondControlX, secondControlY,3, Path.Direction.CW);
    linePath.addCircle(adjustBoundWidth - secondControlX,
            secondControlY,3, Path.Direction.CW);
    linePath.addCircle(adjustBoundWidth - firstControlX, firstControlY,3, Path.Direction.CW);
    linePath.offset(offsetX, offsetY);
}複製代碼

整個過程路徑及控制點變化以下:


至此,箭頭上移的效果,只需根據繩子中心點的位置,平移下載箭頭位置便可;

1.4.直線上下震盪及下載箭頭(Arrow)變承載進度文字的線框形態:


這個過程有如下三點須要考慮:

1.4.1.直線震盪:
該效果僅需持續上下移動二階貝塞爾曲線的控制點便可,再也不多言;

1.4.2.箭頭沿曲線移動:
移動的路線能夠採用一個三階貝塞爾曲線進行模擬,再使用PathMeasure獲取過程當中的實時位置(x、y),關鍵代碼以下:

if (mArrowMovePath.isEmpty()) {
    mArrowMovePath.moveTo(mArrowMovePathRect.left, mArrowMovePathRect.bottom);
    mArrowMovePath.cubicTo(mArrowMovePathRect.left + mArrowMovePathRect.width() / 4,
            mArrowMovePathRect.top,
            mArrowMovePathRect.right,
            mArrowMovePathRect.top,
            mArrowMovePathRect.right, mArrowMovePathRect.bottom);
    mArrowPathMeasure.setPath(mArrowMovePath, false);
    mArrowMovePathLength = mArrowPathMeasure.getLength();
}

mArrowPathMeasure.getPosTan(mArrowMovePathLength * normalizedTime , mArrowMovePoint, null);複製代碼

1.4.3.移動過程當中的下載箭頭形態變換:

我們用rectWidth、rectHeight分別指代下載箭頭底部的矩形部分的寬高,triWidth、triHeight分別指代Arrow頭部的三角形部分的寬高,angle指代下載箭頭的旋轉角度;

只需用ValueAnimator建立一個過程將以上數值進行以下變換:

rectWidth 到 2rectWidth;
rectHeight 到 1.4rectHeight 再到 rectHeight;
triWidth 到 0.65triWidth;
triHeight 到 0.65*triHeight;
angle 由 0 -> -30 -> 20 -> -10 -> 0度;

OK,到這裏,第一部分就能夠告一段落,我們繼續看後面的部分;

2.InProgress(顯示進度中) :


GAStudio哥本次在實現過程當中,沒有實如今移動的過程當中的線框的搖擺,有興趣的同窗能夠本身修改實現,剩餘部分主要講下拉繩的變更:

2.1. 拉繩的變更:


觀察上圖,能夠將拉繩下拉的頂點移動的軌跡近似當作一條折線,先計算出頂點的位置,再分別繪製左、右兩邊的直線,關鍵代碼以下:

private void drawProgressRopePath(
        Canvas canvas, float normalizeProgress, int baselineLen,
        int baseLineX, int baseLineY, int highestPointHeight, int leftLineColor) {
    int halfLen = baselineLen / 2;
    int middlePointX = (int) (baseLineX + baselineLen * normalizeProgress);
    int middlePointY;

    float k = (float) highestPointHeight / halfLen;
    if (normalizeProgress < HALF_NORMALIZED_PROGRESS) {
        middlePointY = (int) (halfLen * k
                * normalizeProgress / HALF_NORMALIZED_PROGRESS) + baseLineY;
    } else {
        middlePointY = (int) (halfLen * k
                * (1 - normalizeProgress) / HALF_NORMALIZED_PROGRESS) + baseLineY;
    }
    // draw right part first
    mBaseLinePaint.setColor(DEFAULT_LOADING_LINE_COLOR);
    canvas.drawLine(middlePointX, middlePointY, baseLineX + baselineLen,
            baseLineY, mBaseLinePaint);

    // draw left part
    mBaseLinePaint.setColor(leftLineColor);
    canvas.drawLine(baseLineX, baseLineY, middlePointX, middlePointY, mBaseLinePaint);
    if (mProgressRopePathRectF == null) {
        mProgressRopePathRectF = new RectF();
    }
    mProgressRopePathRectF.set(baseLineX, baseLineY, baseLineX + baselineLen, middlePointY);
}複製代碼

3.Failed(失敗動畫):

擼完以上gif,咱們能夠把這部分效果分爲以下幾點:
1.線框內的文字變爲Failed而且晃動;
2.繩子上下抖動;
3.繩子左側的白色部分爆炸消失;
4.線框回到最初位置,變且變爲下載箭頭;
5.圓形背景逐漸放大出現;
6.圓形背景和下載箭頭總體縮放;

在這裏,咱們一塊兒看下爆炸效果的實現,其餘部分相對簡單,再也不贅述;

關於爆炸效果,咱們能夠很逼真的模擬,繪製出各式各樣的圓點來模擬,可是因爲點的個數多,大小不一,採用該方式費事費力,而且因爲效果速度快,轉瞬即逝,咱們能夠採用一種簡單而效果看起來差很少的方式,就是隻畫幾個形狀,而後平鋪到整個繩子;

該處主要使用paint的setPathEffect方法將PathEffect設置爲PathDashPathEffect,關鍵代碼以下:

Path cycle = new Path();
// generate bomb point shape
cycle.addCircle(0, 0, mBaseLineStrokeWidth / 2, Path.Direction.CCW);
cycle.addCircle(mBaseLineStrokeWidth, 0, mBaseLineStrokeWidth / 3, Path.Direction.CCW);
cycle.addCircle(mBaseLineStrokeWidth * 2, 0, mBaseLineStrokeWidth / 4, Path.Direction.CCW);
cycle.addCircle(mBaseLineStrokeWidth * 3, 0, mBaseLineStrokeWidth / 5, Path.Direction.CCW);
mFailedBombPaint = new Paint();
mFailedBombPaint.setStrokeWidth(mBaseLineStrokeWidth);
mFailedBombPaint.setAntiAlias(true);
mFailedBombPaint.setColor(DEFAULT_PROGRESS_LINE_LEFT_COLOR);
mFailedBombPaint.setStyle(Paint.Style.STROKE);

mFailedBombPaint.setPathEffect(new PathDashPathEffect(cycle,
        mBaseLineStrokeWidth * 3, 0, PathDashPathEffect.Style.TRANSLATE));
mFailedBombBellowPaint = new Paint(mFailedBombPaint);
mFailedBombBellowPaint.setPathEffect(new PathDashPathEffect(cycle,
        mBaseLineStrokeWidth * 3, HALF_FULL_ANGLE, PathDashPathEffect.Style.TRANSLATE));複製代碼

4.Done(完成動畫):


擼完以上gif, 咱們能夠將該部分歸納爲如下部分:

1.線框繞Y軸旋轉,並由100%變換爲done;
2.線框隨進度條收縮到最中心;
3.線框在中心點晃動;
4.線框變換爲下載箭頭,圓形背景復出;
5.圓形背景和下載箭頭總體縮放,伴隨下載箭頭上下晃動;

該部分我們一塊兒看下第一條的實現,即Canvas裏如何實現僞三維變換;
Canvas中只有rotate函數,也就是在二維平面內進行旋轉,不能實現如上的繞Y軸旋轉,相似效果須要藉助Camera來實現,關鍵代碼以下:

float angle;
String str;
if (normalizedTime <= HALF_NORMALIZED_PROGRESS) {
    str = FULL_PROGRESS_STR;
    angle = HALF_FULL_ANGLE * normalizedTime;
    mProgressTextPaint.setColor(DEFAULT_PROGRESS_TEXT_COLOR);
} else {
    str = FULL_PROGRESS_DONE_STR;
    angle = HALF_FULL_ANGLE * normalizedTime + HALF_FULL_ANGLE;
    mProgressTextPaint.setColor(DEFAULT_DONE_PROGRESS_TEXT_COLOR);
}
if (mCamera == null) {
    mCamera = new Camera();
}
mCamera.save();
mCamera.rotateY(angle);
mCamera.getMatrix(mArrowRotateMatrix);
mCamera.restore();
// 保證繞Arrow的中心進行旋轉
mArrowRotateMatrix.preTranslate(-mArrowRectF.centerX(), -mArrowRectF.centerY());
mArrowRotateMatrix.postTranslate(mArrowRectF.centerX(), mArrowRectF.centerY());
mLastArrowOffsetX = (int) (mBaseLineX + mBaseLineLen - mArrowRectF.width() / 2);
mLastArrowOffsetY = (int) (mBaseLineY - mArrowRectF.height());
canvas.save();
canvas.translate(mLastArrowOffsetX, mLastArrowOffsetY);
// 應用上述Camera變換的結果
canvas.concat(mArrowRotateMatrix);
mDefaultPaint.setColor(DEFAULT_ARROW_COLOR);
// 繪製Arrow
canvas.drawPath(mArrowPath, mDefaultPaint);
mProgressTextPaint.getTextBounds(str,
        0, str.length(), mProgressTextRect);
// 文字
canvas.drawText(str,
        mArrowRectF.left + (mArrowRectF.width() - mProgressTextRect.width()) / 2,
        mArrowRectF.bottom - mArrowRectF.height() / 2, mProgressTextPaint);
canvas.restore();複製代碼

至此,該效果的核心邏輯我們已經分析完畢,實現效果以下:

成功部分:


失敗部分:

你覺得到這裏就結束了嗎?No-No-No,做爲一個負責任的開發者,最後我們加上合理的自定義屬性,以方便使用者自行定義:

<declare-styleable name="GADownloadingView">
    <attr name="arrow_color" format="color" />
    <attr name="loading_circle_back_color" format="color" />
    <attr name="loading_line_color" format="color" />
    <attr name="progress_line_color" format="color" />
    <attr name="progress_text_color" format="color" />
    <attr name="done_text_color" format="color" />
</declare-styleable>複製代碼

最後附上QQ技術交流羣和 github 地址,喜歡的同窗歡迎follow和star:

若是你想看 GAStudio Github主頁,請戳這裏
若是你想看 GAStudio更多技術文章,請戳這裏
QQ技術交流羣:277582728;
github地址: github.com/Ajian-studi…

相關文章
相關標籤/搜索