SeniorUI0402_LinearGradient线性渐变:霓虹灯文字

高级UI汇总​​​​​​​
SeniorUI04_Paint高级渲染Shader使用
###1 Effect Picture
这里写图片描述

###2 Demo
MyGradientView
###3 RequireMent

  1. 霓虹灯文字效果
  2. 文字内容部分高亮显示
  3. 文字从左往右,文字逐渐高亮,到达右侧后,反向动态显示

###4 Theory

  • 自定义View
  • Shader中的LinearGradient实现高亮(不同颜色线性渐变)
  • Matrix + postInvalidateDelayed+ LinearGradient.setLocalMatrix实现动态效果

##5 API

####LinearGradient构造1:
LinearGradient(
float x0,
float y0,
float x1,
@ColorInt int color0,
@ColorInt int color1,
@NonNull TileMode tile)

  • x0 渐变色开始x坐标
  • y0 渐变色开始y坐标
  • x1 渐变色结束x坐标
  • y1 渐变色结束y坐标
  • color0 开始颜色
  • color1 结束颜色
  • TileMode平铺模式
    ####LinearGradient构造2:
    LinearGradient(
    float x0,
    float y0,
    float x1,
    float y1,
    @NonNull @ColorInt int colors[],
    @Nullable float positions[],
    @NonNull TileMode tile) {
  • x0 渐变色开始x坐标
  • y0 渐变色开始y坐标
  • colors 渐变色数组
  • positions 渐变色间隔
  • TileMode平铺模式

##6 Core Code

public class LinearGradientTextView extends TextView{
    private TextPaint mPaint;

    private LinearGradient mLinearGradient ;
    private Matrix mMatrix;

    private float mTranslate;
    private float DELTAX = 20;

    public LinearGradientTextView(Context context) {
        super(context);
    }

    public LinearGradientTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

   @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        // 拿到TextView的画笔
        mPaint = getPaint();
        String text = getText().toString();
        float textWith = mPaint.measureText(text);
        // 3个文字的宽度
        int gradientSize = (int) (textWith / text.length() * 3);

        // 从左边-gradientSize开始,即左边距离文字gradientSize开始渐变
        mLinearGradient = new LinearGradient(-gradientSize,0,0,0,new int[]{
                0x22ffffff, 0xffffffff, 0x22ffffff},null, Shader.TileMode.CLAMP
        );

        mPaint.setShader(mLinearGradient);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mTranslate += DELTAX;
        float textWidth = getPaint().measureText(getText().toString());
        if(mTranslate > textWidth + 1 || mTranslate < 1){
            DELTAX = - DELTAX;
        }

        mMatrix = new Matrix();
        mMatrix.setTranslate(mTranslate, 0);
        mLinearGradient.setLocalMatrix(mMatrix);
        postInvalidateDelayed(50);

    }
}

猜你喜欢

转载自blog.csdn.net/baopengjian/article/details/80652149