文章来自http://blog.csdn.net/zhaodecang
在音乐播放器项目中使用到酷狗音乐展示歌词的效果,需要支持修改字体、颜色、渐变色等功能
截图如下(效果不是很好,请下载Demo查看)
歌词绘制流程核心代码如下(具体实现过程请看Github源码)
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 中心Y坐标 float centerY = getHeight() / 2 + mTextSize / 2 + mAnimOffset; // 无歌词文件 if (!hasLrc()) { float centerX = (getWidth() - mCurrentPaint.measureText(label)) / 2; canvas.drawText(label, centerX, centerY, mCurrentPaint); return; } // 画当前行 String currStr = mLrcTexts.get(mCurrentLine); float currX = (getWidth() - mCurrentPaint.measureText(currStr)) / 2; canvas.drawText(currStr, currX, centerY, mCurrentPaint); // 画当前行上面的 for (int i = mCurrentLine - 1; i >= 0; i--) { String upStr = mLrcTexts.get(i); float upX = (getWidth() - mNormalPaint.measureText(upStr)) / 2; float upY = centerY - (mTextSize + mDividerHeight) * (mCurrentLine - i); // 超出屏幕停止绘制 if (upY - mTextSize < 0) { break; } canvas.drawText(upStr, upX, upY, mNormalPaint); } // 画当前行下面的 for (int i = mCurrentLine + 1; i < mLrcTimes.size(); i++) { String downStr = mLrcTexts.get(i); float downX = (getWidth() - mNormalPaint.measureText(downStr)) / 2; float downY = centerY + (mTextSize + mDividerHeight) * (i - mCurrentLine); // 超出屏幕停止绘制 if (downY > getHeight()) { break; } canvas.drawText(downStr, downX, downY, mNormalPaint); } }