自定义view-玩转字体变色

自定义view-玩转字体变色_第1张图片
效果图.gif

定义属性

 
        
        
    

自定义布局:主要方法是:canvas.clipRect

public class ColorTrackTextView extends android.support.v7.widget.AppCompatTextView {
    // 1. 实现一个文字两种颜色 - 绘制不变色字体的画笔,原始的颜色
    private Paint mOriginPaint;
    // 2. 实现一个文字两种颜色 - 绘制变色字体的画笔,变色的颜色
    private Paint mChangePaint;
    //当前的进度
    private float mCurrentProgress = 0.0f;
    // 3.实现不同朝向
    private Direction mDirection = Direction.LEFT_TO_RIGHT;


    public enum Direction {
        //从左到右
        LEFT_TO_RIGHT,
        //从右到左
        RIGHT_TO_LEFT
    }



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

    public ColorTrackTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ColorTrackTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint(context, attrs);
    }

    /**
     * 初始化画笔
     */
    private void initPaint(Context context, AttributeSet attrs) {
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ColorTrackTextView);

        int originColor = array.getColor(R.styleable.ColorTrackTextView_originColor, getTextColors().getDefaultColor());
        int changeColor = array.getColor(R.styleable.ColorTrackTextView_changeColor, getTextColors().getDefaultColor());

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

        // 回收
        array.recycle();
    }

    /**
     * 根据颜色获取画笔
     */
    private Paint getPaintByColor(int color) {
        Paint paint = new Paint();
        // 设置颜色
        paint.setColor(color);
        // 设置抗锯齿
        paint.setAntiAlias(true);
        // 防抖动
        paint.setDither(true);
        // 设置字体的大小  就是TextView的字体大小
        paint.setTextSize(getTextSize());
        return paint;
    }

    /**
     * 一个文字两种颜色
     * 利用clipRect可以裁剪 ,左边用一个画笔  而右边用另一个画笔去画 不断改变中间值
     */
    @Override
    protected void onDraw(Canvas canvas) {
        //super.onDraw(canvas);不用系统的
        //canvas.clipRect()裁剪
        //根据进度把中间值求出来
        int middle = (int) (mCurrentProgress * getWidth());
        //从左到右绘制,左边是红色,右边是蓝色
        if(mDirection==Direction.LEFT_TO_RIGHT){
            // 绘制变色
            drawText(canvas, mChangePaint , 0, middle);
            drawText(canvas, mOriginPaint, middle, getWidth());
        }
        //从右到左绘制,左边是蓝色,右边是红色
        else if(mDirection==Direction.RIGHT_TO_LEFT){
            // 右边是红色左边是蓝色
            drawText(canvas, mChangePaint, getWidth()-middle, getWidth());
            // 绘制变色
            drawText(canvas, mOriginPaint, 0, getWidth()-middle);
        }

    }
    /**
     * 绘制Text
     */
    private void drawText(Canvas canvas, Paint paint, int start, int end) {
        canvas.save();
        // 绘制不变色
        Rect rect = new Rect(start, 0, end, getHeight());
        canvas.clipRect(rect);
        // 我们自己来画
        String text = getText().toString();
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        // 获取字体的宽度
        int x = getWidth() / 2 - bounds.width() / 2;
        // 基线baseLine
        Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
        int dy = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom;
        int baseLine = getHeight() / 2 + dy;
        canvas.drawText(text, x, baseLine, paint);
        canvas.restore();
    }

    /**
     * 设置方向
     */
    public void setDirection(Direction direction) {
        mDirection = direction;
    }

    /**
     * 设置当前进度
     */
    public void setCurrentProgress(float currentProgress) {
        mCurrentProgress = currentProgress;
        invalidate();
    }

    /**
     * 设置改变颜色
     */
    public void setChangeColor(int changeColor) {
        this.mChangePaint.setColor(changeColor);
    }

    /**
     * 设置原始的原色
     */
    public void setOriginColor(int originColor) {
        this.mOriginPaint.setColor(originColor);
    }
}


主布局:使用的LinearLayout+viewpager




    

        
    


    

Fragment布局




    

itemFragment的实现

public class ItemFragment extends Fragment {
    public static ItemFragment newInstance(String item) {
        ItemFragment itemFragment = new ItemFragment();
        Bundle bundle = new Bundle();
        bundle.putString("title", item);
        itemFragment.setArguments(bundle);
        return itemFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_item,container,false);

        TextView tv = (TextView) view.findViewById(R.id.text_view1);
        Bundle bundle = getArguments();
        tv.setText(bundle.getString("title"));
        return view;
    }
}

主Activity实现文字颜色的变化

private String[] items = {"直播", "推荐", "视频", "图片", "段子", "精华"};
    private LinearLayout mIndicatorContainer;
    private List mIndicators;
    private ViewPager mViewPager;
    private String TAG = "ViewPagerActivity";


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_pager);
        mIndicators = new ArrayList<>();
        mIndicatorContainer = (LinearLayout) findViewById(R.id.indicator_view);
        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        initIndicator();
        initViewPager();


    }

    /**
     * 初始化ViewPager
     */
    private void initViewPager() {
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                ItemFragment itemFragment = ItemFragment.newInstance(items[position]);
                return itemFragment;
            }

            @Override
            public int getCount() {
                return items.length;
            }



            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                super.destroyItem(container, position, object);
            }


        });


        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                // 获取左边
                ColorTrackTextView left = mIndicators.get(position);
                // 设置朝向
                left.setDirection(ColorTrackTextView.Direction.RIGHT_TO_LEFT);
                // 设置进度  positionOffset 是从 0 一直变化到 1 不信可以看打印
                left.setCurrentProgress(1 - positionOffset);

                // 获取右边
                ColorTrackTextView right = mIndicators.get(position + 1);
                right.setDirection(ColorTrackTextView.Direction.LEFT_TO_RIGHT);
                right.setCurrentProgress(positionOffset);

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {
              if (currIndex != mIndicators.size() - 1 && currIndex != 0) {
                    scrollToChild(currIndex, 0);
                }
            }
        });

    }
    private void scrollToChild(int position, int offset) {
        //获取屏幕宽度
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        //计算控件居正中时距离左侧屏幕的距离
        int middleLeftPosition = (screenWidth - mIndicatorContainer.getChildAt(position).getWidth()) / 2;
        //正中间位置需要向左偏移的距离
        offset = mIndicatorContainer.getChildAt(position).getLeft() - middleLeftPosition;
        mHorizontalScrollView.smoothScrollTo(offset, 0);
    }
    /**
     * 初始化可变色的指示器
     */
    private void initIndicator() {
        for (int i = 0; i < items.length; i++) {
            // 动态添加颜色跟踪的TextView
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.weight = 1;
            ColorTrackTextView colorTrackTextView = new ColorTrackTextView(this);
            // 设置两种颜色
            colorTrackTextView.setOriginColor(Color.BLUE);
            colorTrackTextView.setChangeColor(Color.RED);
            colorTrackTextView.setText(items[i]);
            colorTrackTextView.setLayoutParams(params);
            // 把新的加入LinearLayout容器
            mIndicatorContainer.addView(colorTrackTextView);
            // 加入集合
            mIndicators.add(colorTrackTextView);
        }
    }

你可能感兴趣的:(自定义view-玩转字体变色)