音乐播放器歌词的逐字渲染效果
受到Android 自定義控件玩轉字體變色 打造炫酷ViewPager指示器的啟發,決定用這個來仿制大多數音樂播放器的逐字染色效果,效果圖如下:
關鍵點剖析一:逐字染色效果
關鍵代碼如下:
public boolean clipRect(int left, int top, int right, int bottom)這是Canvas的clipRect方法,這個方法可以理解為要在整個畫布上剪切一塊矩形來繪制內容,此矩形以外的內容全部不繪制,也就是形成了上圖的斷層效果。其中left,top,right,bottom分別是左,上,右,下四個端點,right也就是效果圖上的斷層位置。
實現染色效果的思路是,用clipRect將一行文字剪切成兩部分,前半部分用綠色,后邊部分用黑色,根據進度的變化,改變這個剪切點的位置。
關鍵點剖析二:當前播放歌詞的居中效果
這就是要找到畫布的垂直方向上的居中位置。在View的onMeasure方法中獲取整個畫布的高度getMeasuredWidth(),乘以1/2就是中間點的高度。然而這個高度不能作為字的頂部起始位置,否則會偏下,因為字本身也有高度。通過paint.getTextBounds(text, 0, text.length(), mTextBound);方法獲取字體的高度,使用 currentStartY = height / 2 - mTextBound.height() / 2作為字的頂部起始位置剛好居中:
@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec);int width = getMeasuredWidth();mMaxTextWidth = width - getPaddingLeft() - getPaddingRight();mTestTextWidth = Math.min(mMaxTextWidth, measureText(testClipRectText, mPaint));mTestTextStartX = mMaxTextWidth / 2 - mTestTextWidth / 2;lyricManager.confirmLyricState(getMeasuredWidth(), getMeasuredHeight(), mTextOriginColor, mTextChangeColor, mMaxTextWidth, mPaint);}關鍵點剖析三:逐行上移
這里使用了ValueAnimator動畫。targetStartY 是目標位置,currentStartY 是當前位置,通過賦值動畫不停的將currentStartY賦值并刷新視圖,實現上移動畫。
//調整歌詞整體上移一句private void nextLyric() {float targetStartY = currentStartY - (mTextBound.height() * 1.5f);ValueAnimator animator = ValueAnimator.ofFloat(currentStartY, targetStartY).setDuration(1000);animator.addListener(new Animator.AnimatorListener() {@Overridepublic void onAnimationStart(Animator animation) {}@Overridepublic void onAnimationEnd(Animator animation) {}@Overridepublic void onAnimationCancel(Animator animation) {}@Overridepublic void onAnimationRepeat(Animator animation) {}});animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {@Overridepublic void onAnimationUpdate(ValueAnimator animation) {confirmLyricState(mWidth, mHeight, mNormalColor, mChangeColor, mMaxTextWidth, mPaint, currentStartY);currentStartY = (float) ((ValueAnimator) animation).getAnimatedValue();}});animator.start();}詳細請查看:Github上的Demo源碼
總結
以上是生活随笔為你收集整理的音乐播放器歌词的逐字渲染效果的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android 定义数组,Androi
- 下一篇: MyBatis框架的特性