卡拉OK歌词着色原理

与唱吧、全民k歌类似,需要实现卡拉OK歌词随歌曲播放进度而着色。这里不讲lrc,zerc等格式歌词解析,而是着重于歌词着色的实现。

卡拉OK歌词着色原理_第1张图片
avatar

一、基本原理

1、进度计算

当前行歌词文字的总长度:L
当前行歌词播放的总时长:T
当前行歌词播放的进度时间:P (这个P应不断的被计算更新)
则歌词物理着色长度 C = L* (P / T)

2、实现思路

(1)、把文字画出来:
网上其他人的做法都是使用Paint把文字画出来,但是这样实现有一个问题,Paint无法自动换行和处理文字居中显示,就算计算歌词总长度和View宽度比较两者再手动换行,还是无法处理好英文的情况,因为歌词存在空格和单个单词不能分割。这个时候想到日常使用的TextView是能自动处理文字换行的。如果我们的自定义View能像TextView一样自动换行就好了。
跟进TextView发现其换行是:StaticLayout + TextPaint实现的。StaticLayout包裹TextPaint。
先看TextPaint:TextPaint继承与Paint,添加了一些处理文字相关的属性,并没有作妖。

public class TextPaint extends Paint {

    // Special value 0 means no background paint
    @ColorInt
    public int bgColor;
    public int baselineShift;
    @ColorInt
    public int linkColor;
    public int[] drawableState;
    public float density = 1.0f;

于是跟进StaticLayout:
StaticLayout继承于Layout。首先看draw方法,这个是它把文字画出来的入口,看它是如何画出一行行的文字。

/**
     * Draw this Layout on the specified Canvas.
     */
    public void draw(Canvas c) {
        draw(c, null, null, 0);
    }
/**
     * Draw this Layout on the specified canvas, with the highlight path drawn
     * between the background and the text.
     *
     * @param canvas the canvas
     * @param highlight the path of the highlight or cursor; can be null
     * @param highlightPaint the paint for the highlight
     * @param cursorOffsetVertical the amount to temporarily translate the
     *        canvas while rendering the highlight
     */
    public void draw(Canvas canvas, Path highlight, Paint highlightPaint,
            int cursorOffsetVertical) {
        final long lineRange = getLineRangeForDraw(canvas);
        int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
        int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
        if (lastLine < 0) return;

        drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
                firstLine, lastLine);
        drawText(canvas, firstLine, lastLine);
    }

看到最后一行,像是传入了两个参数,一个第一行,一个最后一行,让drawText画画出来。这时候如果我们让StaticLayout处理好换行后,我们利用这个API手动一行一行的画出来该多好。

drawText(canvas, firstLine, lastLine);

跟进去看。。。该死,@hide,非公开API

/**
     * @hide
     */
    public void drawText(Canvas canvas, int firstLine, int lastLine) {
        int previousLineBottom = getLineTop(firstLine);
        int previousLineEnd = getLineStart(firstLine);

前功尽弃?no,山穷水尽疑无路,利用反射获得这个API完全可以柳暗花明。那么其他的我们需要的StaticLayout的能力,尝试性的打个StaticLayout.get惊喜的发现有我们想要的一切,获取总行数、行高、行款等。


卡拉OK歌词着色原理_第2张图片
avatar

这样就解决了换行的问题。

(2)着色问题
,如果把歌词着色分开看,其实一边是高亮色,一边是普通色,高两色逐渐向普通色递进。LinearGradient可以实现渐变色,如果只给LinearGradient两个颜色,那么就能做出两色渐变。

LinearGradient(float x0, float y0, float x1, float y1, int colors[], float positions[], TileMode tile)

注:Android中计算x,y坐标都是以屏幕左上角为原点,向右为x+,向下为y+
第一个参数为线性起点的x坐标
第二个参数为线性起点的y坐标
第三个参数为线性终点的x坐标
第四个参数为线性终点的y坐标
第五个参数为实现渐变效果的颜色的组合
第六个参数为前面的颜色组合中的各颜色在渐变中占据的位置(比重),如果为空,则表示上述颜色的集合在渐变中均匀出现
第七个参数为渲染器平铺的模式,一共有三种
LinearGradient再次不细表,具体需要再去查。
核心绘制代码如下

@Override
    protected void onDraw(Canvas canvas) {
        int lineWidth = 0;
        LinearGradient linearGradient;
        mStaticLayout = new StaticLayout(message, tp, getWidth(), Layout.Alignment.ALIGN_CENTER, 1.2f, 0.0f, false);
        Log.d("Length", "getHeight" + mStaticLayout.getHeight());
        int totalCount = mStaticLayout.getLineCount();
        Method method = null;
        try {
            method = Layout.class.getDeclaredMethod("drawText", new Class[]{Canvas.class, int.class, int.class});
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        method.setAccessible(true);
        for (int i = 0; i < totalCount; i++) {
            //就算在一行填满的情况下,StaticLayout.getLineWidth(i)获得的宽度仍与view.getWidth的宽度存在一定误差,并且总是小于
            float begain = (getWidth() - mStaticLayout.getLineWidth(i)) / 2;
            float end = begain + mStaticLayout.getLineWidth(i);
            lineWidth += mStaticLayout.getLineWidth(i);
            if (lineWidth < progress) {
                linearGradient = new LinearGradient(begain, 0, end, 0, KARAOK_COLORS, new float[]{1.0f, 0.0f}, Shader.TileMode.CLAMP);

            } else if ((lineWidth - progress) < mStaticLayout.getLineWidth(i)) {
                float pos = 1.0f - (lineWidth - progress) / mStaticLayout.getLineWidth(i);
                linearGradient = new LinearGradient(begain, 0, end, 0, KARAOK_COLORS, new float[]{pos, pos}, Shader.TileMode.CLAMP);
            } else {
                linearGradient = new LinearGradient(begain, 0, end, 0, KARAOK_COLORS, new float[]{0.0f, 0.0f}, Shader.TileMode.CLAMP);
            }
            tp.setShader(linearGradient);
            try {
                method.invoke(mStaticLayout, canvas, i, i);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

你可能感兴趣的:(卡拉OK歌词着色原理)