Android自定义View实现不同朝向字体变色

实现效果:
1.一个文字两种颜色
2.实现不同朝向
3.结合ViewPager
思路:TextView可行?系统提供的只能够显示一种颜色,需要自定义View
extends TextView:onMeasure()不需要实现 textColor颜色,textSize字体大小会少很多逻辑。
1.一个文字两种颜色 画
2.能够从左到右,从右到左
3.整合到ViewPager,监听滚动事件

自定义属性,不变化的颜色 originColor 变化的颜色 changeColor

在这里插入图片描述
x要在这个位置
在这里插入图片描述
就等于宽度的一半减去文字的一半。

实现一个文字两种颜色

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    >

    <com.example.customview.customview.colortrack.ColorTrackTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="20sp"
        />

</RelativeLayout>
public class ColorTrackTextView extends TextView {

    //实现一个文字两种颜色---绘制不变色字体的画笔
    private Paint mOriginPaint;
    //实现一个文字两种颜色---绘制变色字体的画笔
    private Paint mChangePaint;
    //实现一个文字两种颜色--当前的进度
    private float mCurrentProgress=0.5f;
    public ColorTrackTextView(Context context) {
        this(context,null);
    }

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

    public ColorTrackTextView(Context context, @Nullable @org.jetbrains.annotations.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, Color.RED);
        int changeColor=array.getColor(R.styleable.ColorTrackTextView_changeColor,Color.BLUE);
        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的字体大小,通过继承TextView可以直接拿
        paint.setTextSize(getTextSize());
        return paint;

    }


    @Override
    protected void onDraw(Canvas canvas) {
        //因为是继承TextView,所以不进行super不然TextView会去画文字
//        super.onDraw(canvas);
        //canvas.clipRect()  裁剪区域
        //根据进度把中间值算出来
        int middle=(int) (mCurrentProgress*getWidth());
        drawText(canvas,mOriginPaint,0,middle);
        //绘制变色
        drawText(canvas,mChangePaint,middle,getWidth());

    }


    //1.个文字两种颜色
    //利用clipRect的API 可以裁剪 左边用一个画笔去画  右边用另一个画笔去画  不断的改变中间值 从而实现变化颜色效果
    public void drawText(Canvas canvas,Paint paint,int start,int end){
        //因为要调两次drawText如果不对画布进行save和restore的话,画布只会展示第一次调用的画笔
        canvas.save();
        //根据进度把中间值算出来
        String text=getText().toString();
        Rect bounds=new Rect();
        //clipRect裁剪区域,左--上---右---下
        canvas.clipRect(start,0,end,getHeight());
        paint.getTextBounds(text,0,text.length(),bounds);
        //获取字体的宽度
        int x=getWidth()/2-bounds.width()/2;
        //基线baseLine
        Paint.FontMetricsInt fontMetrics=paint.getFontMetricsInt();
        //bottom是正的.top是负的
        int dy=(fontMetrics.bottom-fontMetrics.top)/2-fontMetrics.bottom;
        int baseLine=getHeight()/2+dy;
        canvas.drawText(text,x,baseLine,paint);
        canvas.restore();

    }


}

在这里插入图片描述

不同朝向

点击按钮实现不同朝向的变色

public class ColorTrackTextView extends TextView {

    //1.实现一个文字两种颜色---绘制不变色字体的画笔
    private Paint mOriginPaint;
    //1.实现一个文字两种颜色---绘制变色字体的画笔
    private Paint mChangePaint;
    //1.实现一个文字两种颜色--当前的进度
    private float mCurrentProgress=0.0f;
    //2.实现不同的朝向
    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, Color.BLACK);
        int changeColor=array.getColor(R.styleable.ColorTrackTextView_changeColor,Color.BLACK);
        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的字体大小,通过继承TextView可以直接拿
        paint.setTextSize(getTextSize());
        return paint;

    }


    @Override
    protected void onDraw(Canvas canvas) {
        //因为是继承TextView,所以不进行super不然TextView会去画文字
//        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 {//从右到左
            drawText(canvas,mChangePaint,getWidth()-middle,getWidth());//右边是红色左边是黑色
            //绘制变色
            drawText(canvas,mOriginPaint,0,getWidth()-middle);
        }


    }


    //1.个文字两种颜色
    //利用clipRect的API 可以裁剪 左边用一个画笔去画  右边用另一个画笔去画  不断的改变中间值 从而实现变化颜色效果
    public void drawText(Canvas canvas,Paint paint,int start,int end){
        //因为要调两次drawText如果不对画布进行save和restore的话,画布只会展示第一次调用的画笔
        canvas.save();
        //根据进度把中间值算出来
        String text=getText().toString();
        Rect bounds=new Rect();
        //clipRect裁剪区域,左--上---右---下
        canvas.clipRect(start,0,end,getHeight());
        paint.getTextBounds(text,0,text.length(),bounds);
        //获取字体的宽度
        int x=getWidth()/2-bounds.width()/2;
        //基线baseLine
        Paint.FontMetricsInt fontMetrics=paint.getFontMetricsInt();
        //bottom是正的.top是负的
        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){
        this.mDirection=direction;
    }

    public void setCurrentProgress(float currentProgress){
        this.mCurrentProgress = currentProgress;
        invalidate();
    }


}

<?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:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    >

    <com.example.customview.customview.colortrack.ColorTrackTextView
        android:id="@+id/color_track_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="20sp"
        app:changeColor="@color/red"
        app:originColor="@color/black"
        />

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

</LinearLayout>

在这里插入图片描述

结合ViewPager

LinearLayout(代码添加变色的View)+ViewPager
主要代码如下:

public class ViewPagerActivity extends AppCompatActivity {

    private String[] items ={"直播","推荐","视频","图片","段子","精华"};
    private LinearLayout mIndicatorContainer;//变成通用的
    private List<ColorTrackTextView> 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();
    }

    private void initViewPager() {
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return ItemFragment.newInstance(items[position]);
            }

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

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                //position 当前的位置
                //positionOffset 滚动偏移量 代表滚动的 0 - 1百分比
                ColorTrackTextView left = mIndicators.get(position);
                left.setDirection(ColorTrackTextView.Direction.RIGHT_TO_LEFT);
                left.setCurrentProgress(1-positionOffset);
                try {
                    ColorTrackTextView right = mIndicators.get(position+1);
                    right.setDirection(ColorTrackTextView.Direction.LEFT_TO_RIGHT);
                    right.setCurrentProgress(positionOffset);
                }catch (IndexOutOfBoundsException e){

                }
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    /**
     * 初始化可变色的指示器
     */
    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.setTextSize(20);
            colorTrackTextView.setChangeColor(Color.RED);
            colorTrackTextView.setText(items[i]);
            colorTrackTextView.setLayoutParams(params);
            //把新的加入LinearLayout容器
            mIndicatorContainer.addView(colorTrackTextView);
            //加入集合
            mIndicators.add(colorTrackTextView);
        }

    }

}

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;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable  ViewGroup container, @Nullable  Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_item,null);
        TextView tv=(TextView) view.findViewById(R.id.text);
        Bundle bundle = getArguments();
        tv.setText(bundle.getString("title"));
        return view;
    }
}

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

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="111" />

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


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/indicator_view"
        android:orientation="horizontal"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        />

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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值