Android实现卡拉OK字幕效果方法

1,使用两个TextView叠加实现,第一个全部长度,第二个长度是零,然后逐步增加;



            

            
 
  
2,自定义TextView,重写onDraw方法,使用Gradient实现,代码段如下:
protected void onDraw(Canvas canvas) {
        //super.onDraw(canvas);
        int length = (int) (getTextSize() * getText().length());// 得到整个歌曲的长度
        int newLength = length * linePosition / 255;
        float newP = newLength / length;
        float p = (newP == 0) ? 0 : (newP - 0.01F);

        Shader shader1 = null;
        if (linePosition > 0) {
            //shader1 = new LinearGradient(0, 0, newLength, 0, new int[]{Color.GREEN,  Color.RED}, new float[]{p, 1-p}, Shader.TileMode.CLAMP);
        } else {
            //shader1 = new LinearGradient(0, 0, length, 0, Color.RED, Color.RED, Shader.TileMode.CLAMP);
        }

        //shader1 = new LinearGradient(0, 0, newLength, 0, new int[]{Color.RED, Color.RED, Color.GREEN, Color.GREEN}, new float[]{0, p, newP, 1}, Shader.TileMode.CLAMP);
        //paint.setShader(shader1);
        shader1 = new LinearGradient(0, 0, newP, 0, new int[]{Color.RED, Color.RED}, null, Shader.TileMode.CLAMP);
        Shader shader2 = new LinearGradient(0, 0, length, 0, Color.GREEN, Color.GREEN, Shader.TileMode.CLAMP);
        Shader mComposeShader = new ComposeShader(shader1, shader2, PorterDuff.Mode.DST_OVER);
        paint.setShader(mComposeShader);

        canvas.drawText(getText().toString(), 0, getTextSize() - 10, paint);
    }


 
  
 
  
 
  
 
 

你可能感兴趣的:(android)