爲了增強對自定義 View 的認知以及開發能力,我計劃這段時間陸續來完成幾個難度從易到難的自定義 View,並簡單的寫幾篇博客來進行介紹,全部的代碼也都會開源,也但願讀者能給個 star 哈 GitHub 地址:github.com/leavesC/Cus… 也能夠下載 Apk 來體驗下:www.pgyer.com/CustomViewjava
先看下效果圖:git
WaveLoadingView 和上一節的 WaveView 相似,但比之多了一個顏色隨波浪起伏而變化的文本,且形狀也變爲了圓形。此處波浪的繪製思路與上一節同樣,重點就在於文本的繪製順序以及畫布的裁切github
繪製流程分爲如下幾步:canvas
private Path circlePath = new Path();
private Path wavePath = new Path();
@Override
protected void onDraw(Canvas canvas) {
textPaint.setColor(waveColor);
drawText(canvas, textPaint, String.valueOf(text));
wavePath.reset();
wavePath.moveTo(-waveWidth + animatedValue, size / 2.2f);
for (float i = -waveWidth; i < size + waveWidth; i += waveWidth) {
wavePath.rQuadTo(waveWidth / 4, -waveHeight, waveWidth / 2, 0);
wavePath.rQuadTo(waveWidth / 4, waveHeight, waveWidth / 2, 0);
}
wavePath.lineTo(size, size);
wavePath.lineTo(0, size);
wavePath.close();
circlePath.reset();
circlePath.addCircle(centerX, centerY, radius - 1, Path.Direction.CCW);
circlePath.op(wavePath, Path.Op.INTERSECT);
canvas.drawPath(circlePath, wavePaint);
canvas.clipPath(circlePath);
textPaint.setColor(downTextColor);
drawText(canvas, textPaint, String.valueOf(text));
}
private void drawText(Canvas canvas, Paint textPaint, String text) {
Rect rect = new Rect(0, 0, size, size);
textPaint.setTextAlign(Paint.Align.CENTER);
Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
float top = fontMetrics.top;
float bottom = fontMetrics.bottom;
int centerY = (int) (rect.centerY() - top / 2 - bottom / 2);
canvas.drawText(text, rect.centerX(), centerY, textPaint);
}
複製代碼