自定义View:02-滑动变色的字体

效果图如下:


滑动文字.gif

一、自定义属性
1.1、字体要变的颜色
1.2、字体不变的颜色
二、继承TextView
2.1、初始化画笔 两个字体画笔 :变色与不变色
2.2、onDraw() : 通过两个画笔(paint)画出同一位置的两次文字,
* 通过canvas.clipRect() (画布的裁剪方法),裁剪出要显示文字的指定区域,
* 通过裁剪方法、与Paint(画笔)定义的颜色,可以实现同一文字不同颜色效果显示
三 、实现文字变色的朝向 :左到右、右到左
四、使用
与viewPager 的监听方法结合,通过加减偏移量 算出字体要显示的部分区域,达到要实现的效果

实现

1、自定义属性:

没有attrs.xml 文件就新建一个


image.png

attrs.xml

 <declare-styleable name="colorTextView">
    <!--1、初始化颜色-->
        <attr name="originColor" format="color"/> 
    <!--1、变化后的颜色-->
        <attr name="changeColor" format="color"/>
    </declare-styleable>

2、新建 ColorTextView_02 类,继承TextView

@SuppressLint("AppCompatCustomView")
public class ColorTextView_02 extends TextView {
    //不变色字体的画笔
    private Paint mOriginPaint;
    //改变颜色字体的画笔
    private Paint mChangePaint;

    private float mCurrentProgress = 0f;//中心值

    private Direction mDirection=Direction.LEFT_TO_RIGHT; //方向

    /**
     * 实现思路
     * 1、创建自定义属性:1.1、字体要变的颜色 1.2、字体不变的颜色
     * 2、自定义TextView ,继承相关的属性 :获取文字的大小 、颜色
     * 3、初始化画笔 两个字体画笔 :变色与不变色
     * 4、绘制 :通过两个画笔(paint)画出同一位置的两次文字,
     *    通过canvas.clipRect() (画布的裁剪方法),裁剪出要显示文字的指定区域,
     *    通过裁剪方法、与Paint(画笔)定义的颜色,可以实现同一文字不同颜色效果显示,
     * 5、实现文字变色的朝向 :左到右、右到左
     *  6、与viewPager 的监听方法结合,通过加减偏移量 算出字体要显示的部分区域,达到要实现的效果
     */

    /**
     * 左到右变色
     * 右到左变色
     */
    public enum Direction{
        LEFT_TO_RIGHT,RIGHT_TO_LEFT
    }

    public ColorTextView_02(Context context) {
        this(context, null);
    }

    public ColorTextView_02(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ColorTextView_02(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint(context, attrs);
    }

    /**
     * 初始化画笔
     *
     * @param context
     * @param attrs
     */
    private void initPaint(Context context, AttributeSet attrs) {
        //自定义属性
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.colorTextView);
        int originColor = array.getColor(R.styleable.colorTextView_originColor, getTextColors().getDefaultColor());
        int changeColor = array.getColor(R.styleable.colorTextView_changeColor, getTextColors().getDefaultColor());

        mOriginPaint = getPaintByColor(originColor);
        mChangePaint = getPaintByColor(changeColor);
    }

    /**
     * 根据颜色获取画笔
     */
    private Paint getPaintByColor(int color) {
        Paint paint = new Paint();
        paint.setColor(color);
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setTextSize(getTextSize());
        return paint;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //中心值
        int middle = (int) (mCurrentProgress * getWidth());

        if (mDirection==Direction.LEFT_TO_RIGHT){
            //不变色的字体
            drawText(canvas,mChangePaint , 0, middle);
            //变色的字体
            drawText(canvas,mOriginPaint , middle, getWidth());
        }else {
            //不变色的字体
            drawText(canvas, mChangePaint, getWidth()-middle, getWidth());
            //变色的字体
            drawText(canvas, mOriginPaint, 0, getWidth()-middle);
        }

    }

    /**
     * 绘制Text
     *
     * @param canvas
     * @param paint
     * @param start
     * @param end
     */
    public void drawText(Canvas canvas, Paint paint, int start, int end) {
        canvas.save(); //保存

        String text = getText().toString();//文字

        //裁剪
        Rect rect = new Rect(start, 0, end, getHeight());
        canvas.clipRect(rect);

        //获取字体的宽度
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);

        //获取字体横线中心的位置
        int x = getWidth() / 2 - bounds.width() / 2;

        //基线baseLine
        Paint.FontMetricsInt fontMetricsInt = paint.getFontMetricsInt();
        int dy = (fontMetricsInt.bottom - fontMetricsInt.top) / 2 - fontMetricsInt.bottom;//基线到底部的距离
        int baseLine = getHeight() / 2 + dy; //获取基线

        //绘制文字
        canvas.drawText(text, x, baseLine, paint);

        canvas.restore();

    }

    //进度
    public void setCurrentProgress(float progress) {
        mCurrentProgress = progress;
        invalidate();
    }

    //朝向
    public void setDirection(Direction direction){
        this.mDirection=direction;
    }

    //设置不变色的字体
    public void setOriginColor(int originColor){
        this.mOriginPaint.setColor(originColor);
    }

    //设置要变色的字体
    public void setChangeColor(int changeColor){
        this.mChangePaint.setColor(changeColor);
    }
}


3、使用

view_text_02.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"

    android:padding="16dp">

    <com.example.view_day01.View.ColorTextView_02
        android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="自定义"
        android:textSize="20sp"
        app:changeColor="@color/colorAccent" />

    <Button
        android:id="@+id/left_ToRight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:text="左到右" />

    <Button
        android:id="@+id/right_ToLeft"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="右到左" />

    <LinearLayout
        android:id="@+id/colorView_linear"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal"/>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="10dp"
        android:layout_weight="1" />
</LinearLayout>

fragment:

public class TextFragment_02 extends Fragment {
    private Button toRight, toLeft;
    private ColorTextView_02 colorView;
    private static final String TAG = "TextFragment_02";
    private ViewPager viewPager;
    private List<Fragment> fragmentList;
    private ViewPagerAdapter pagerAdapter;
    private List<ColorTextView_02> colorTextViewList;
    private LinearLayout colorView_linear;
    private String[] item = {"段子", "视频", "漫画", "小说", "军事"};

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.view_text_02, container, false);
        init(view);
        initIndicator();
        setViewPager();
        return view;
    }

    private void init(View view) {
        colorView = view.findViewById(R.id.text_view);
        toRight = view.findViewById(R.id.left_ToRight);
        toLeft = view.findViewById(R.id.right_ToLeft);
        viewPager = view.findViewById(R.id.viewPager);
        colorView_linear = view.findViewById(R.id.colorView_linear);
        colorTextViewList = new ArrayList<>();
        fragmentList = new ArrayList<>();
        click();
    }

    /**
     * 初始化TabLayout
     */
    private void initIndicator() {
        for (int i = 0; i < item.length; i++) {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.weight = 1;
            ColorTextView_02 view = new ColorTextView_02(getContext());
            view.setTextSize(20);
            view.setChangeColor(Color.RED);
            view.setText(item[i]);
            view.setLayoutParams(params);

            colorView_linear.addView(view);
            colorTextViewList.add(view);
            fragmentList.add(new PageFragment(item[i]));
        }
    }

    /**
     * 监听ViewPager的滑动
     */
    private void setViewPager() {
        FragmentManager fragmentPagerAdapter = getActivity().getSupportFragmentManager();
        pagerAdapter = new ViewPagerAdapter(fragmentPagerAdapter);
        viewPager.setAdapter(pagerAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            //操作前面的字体
                ColorTextView_02 view_02 = colorTextViewList.get(position);
                view_02.setDirection(ColorTextView_02.Direction.RIGHT_TO_LEFT);
                view_02.setCurrentProgress(1 - positionOffset);

                //操作后面的字体
                try {
                    ColorTextView_02 view = colorTextViewList.get(position+1);
                    view.setDirection(ColorTextView_02.Direction.LEFT_TO_RIGHT);
                    view.setCurrentProgress(positionOffset);
                }catch (Exception ignored){

                }

            }

            @Override
            public void onPageSelected(int position) {
                Log.d(TAG, "onPageSelected: " + position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                Log.d(TAG, "onPageScrollStateChanged: " + state);
            }
        });
    }

    /**
     * 点击事件
     */
    private void click() {
        toRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                leftToRight();
            }
        });
        toLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rightToLeft();
            }
        });
    }

    //从左到右变色
    private void leftToRight() {
        colorView.setDirection(ColorTextView_02.Direction.LEFT_TO_RIGHT);
        ValueAnimator animator = ObjectAnimator.ofFloat(0, 1);
        animator.setDuration(2000);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Log.d(TAG, "onAnimationUpdate: " + (float) animation.getAnimatedValue());
                colorView.setCurrentProgress((float) animation.getAnimatedValue());
            }
        });
        animator.start();
    }

    //从右到左变色
    private void rightToLeft() {
        colorView.setDirection(ColorTextView_02.Direction.RIGHT_TO_LEFT);
        ValueAnimator animator = ObjectAnimator.ofFloat(0, 1);
        animator.setDuration(2000);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                colorView.setCurrentProgress((float) animation.getAnimatedValue());
            }
        });
        animator.start();
    }

    /**
     * ViewPager 适配器
     */
    class ViewPagerAdapter extends FragmentPagerAdapter {

        public ViewPagerAdapter(@NonNull FragmentManager fm) {
            super(fm);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }
    }
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271