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

news2024/9/19 10:45:48

实现效果:
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>

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2095881.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

OpenAI Whisper API (InvalidRequestError)

题意: OpenAI Whisper API&#xff08;无效请求错误&#xff09; 问题背景&#xff1a; Im trying to use OpenAI Whisper API to transcribe my audio files. When I run it by opening my local audio files from disk, it worked perfectly. Now Im developing a FastAPI e…

学习WebGl基础知识(二)

学习目标&#xff1a; 掌握WebGl基础知识 学习内容&#xff1a; 创建一个Webgl程序 创建三维上下文对象创建顶点着色器和片元着色器创建和编译顶点着色器和片元着色器创建着色器程序对象绘制图元 创建一个Webgl程序 1.第一步获取画布&#xff0c;创建三维上下文对象 <ca…

一些硬件知识(十七)

电源芯片选型&#xff1a; 1.考虑拓扑结构 2.考虑功率&#xff0c;从而决定自行搭建电路还是选择芯片 3.对于低功耗产品&#xff0c;静态电流是非常重要的因素&#xff0c;一定重要考虑&#xff1a; 同步buck省去了续流二极管&#xff0c;效率比异步的高。 如果真的比耐压值…

ESP32小车:1.硬件模块与连接

一、硬件模块 总的元器件清单:亚克力板(三轮),两个普通减速电机,一个开关模块,一个 首先,需要一块亚克力单层底板,推荐随便在淘宝上买一块2WD亚克力单层板,比如: 最好亚克力板自带电机,买一套也不过15块。如果没有需另外购买两个普通TT直流减速电机和轮子。…

基于yolov8的102种昆虫检测系统python源码+onnx模型+评估指标曲线+精美GUI界面

【算法介绍】 基于YOLOv8的102种昆虫检测系统是一款高效、准确的昆虫识别工具&#xff0c;它利用YOLOv8这一先进的目标检测算法&#xff0c;实现了对102种不同昆虫的实时检测与识别。该系统在农业、生态研究、生物多样性保护等多个领域具有广泛的应用价值。 YOLOv8算法以其高…

HTML沙漏爱心

目录 写在前面 完整代码 下载代码 代码分析 系列文章 写在最后 写在前面 教你用HTML语言实现炫酷的沙漏爱心,该代码不仅可以用电脑运行,手机、平板也可以直接运行哦。 完整代码 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><…

【Linux】:文件IO

目录 1.C文件接口 1.1 当前路径是什么&#xff1f; 1.2 "w"和"a"​编辑 2.系统文件I/O 2.1 "比特宏"标识符的实现: 2.2 open 1.系统默认创建文件的权限只写 2.设置新建文件的权限 3. 覆盖写/清空写/追加写 3.访问文件的本质 3.1 文件…

茴香豆Web实践

茴香豆 是由书生浦语团队开发的一款开源、专门针对国内企业级使用场景设计并优化的知识问答工具。 茴香豆特点&#xff1a; 三阶段 Pipeline &#xff08;前处理、拒答、响应&#xff09;&#xff0c;提高相应准确率和安全性 打通微信和飞书群聊天&#xff0c;适合国内知识问…

提高工作效益方法(一)

目录 如何提高工作效率? 如何提高工作效率?&#xff08;每日工作安排&#xff09; 怎么在职场做好时间管理&#xff1f; 如何提高工作效率? 提高工作效率的关键在于采用一系列策略和方法&#xff0c;以确保工作能够高效、有序地进行。通过这些方法&#xff0c;可以有效地提…

【whisper】使用whisper实现语音转文字

whisper需要ffmpeg支持 官网下载ffmpeg https://www.gyan.dev/ffmpeg/builds/下载完毕后解压放到合适的位置 添加环境变量 在cmd中输入以下 ffmpeg -version出现下面结果代表成功 安装whisper pip install openai-whisper在vscode中运行 测试代码 import whisperif __n…

【c++】cout打印char * 或者char[]的细节详解

目录 char* 类型 1.打印指向的字符串 2.打印指针指向的地址 问题描述 解决方法 char型数组 1. 想要输出字符串 2. 想输出字符数组的地址 printf 和cout 的对比 1.打印首字符 2.打印字符串 3.打印字符串首地址 &#x1f497;感谢阅读&#xff01;&#x1f497; char*…

新火种AI|减脂增肌没捷径?对不起,那是AI 出现以前的事情了...

作者&#xff1a;小岩 编辑&#xff1a;彩云 对于很多人来说&#xff0c;“拥有完美的身材”是人生的重要目标之一&#xff0c;练出好身材的人也会以此为傲&#xff0c;会把自己的好身材po到社交媒体上。换个角度来说&#xff0c;为了让自己社交媒体上的形象足够完美&#xf…

Axure RP下载+详细安装步骤资源百度云盘分享

众所周知&#xff0c;Axure全称“axure rp”&#xff0c;是一款专业的快速原型设计工具。 它能帮助网站需求设计者&#xff0c;快捷而简便的创建基于网站构架图的带注释页面示意图、操作流程图、以及交互设计&#xff0c;并可自动生成用于演示的网页文件和规格文件&#xff0c…

小琳python课堂:Python核心概念 类和对象

大家好&#xff0c;这里是小琳python课堂&#xff01;今天我们来聊聊Python中的类&#xff08;Class&#xff09;和对象&#xff08;Object&#xff09;&#xff0c;这是面向对象编程&#xff08;OOP&#xff09;的核心概念哦&#xff01;&#x1f31f; 面向对象编程就像是用“…

基于 INFINI Pizza 为 Hugo 静态站点添加搜索功能

INFINI Pizza 是 INFINI Labs 即将发布的一个基于 Rust 编写的搜索引擎&#xff08;即将完全开源&#xff09;&#xff0c;目前已经完成基本的搜索能力&#xff0c;并且基于 INFINI Pizza 的核心引擎&#xff0c;提供了一个 WASM 版本的超轻量级内核&#xff0c;可以很方便的嵌…

MicroNet关键代码解读(Micro-block与Dynamic Shift-Max的实现代码)

论文地址&#xff1a;https://arxiv.org/pdf/2011.12289 中文翻译&#xff1a;https://hpg123.blog.csdn.net/article/details/141772832?spm1001.2014.3001.5502 发表时间&#xff1a;2022 项目地址&#xff1a;https://github.com/liyunsheng13/micronet 在MicroNet论文中提…

查文献技巧,数模国赛必须掌握!

参加数学建模竞赛&#xff0c;拿到题目后第一件事就是去查文献&#xff0c;把题目的背景知识看懂。本文介绍查文献的一些技巧。 先看硕博士论文 硕博论文会对研究的问题有详细的背景和基础知识介绍&#xff0c;可帮助我们快速理解题目。 有个经典段子&#xff1a;学士、硕士…

对字符、字符串的研究

每日一背 C的字符串很特殊 //返回字符 char test2() {return p; } //返回整数 int test2() {return 90; } 其实字符串本就是很特殊的存在。字符型、整数算一类&#xff0c;但是字符串型区别前两个类。整数、字符都返回的是一个值&#xff0c;所以可以直接在主函数里面cout不…

《黑神话:悟空》火出圈儿,揭秘幕后实时渲染技术

游戏一度因被贴上“不务正业”、“虚度光阴”的标签而备受争议&#xff0c;然而随着该产业的蓬勃发展&#xff0c;一些游戏被纳入体育竞技项目&#xff0c;如今游戏领域吸引越来越多人的目光。当下火爆全网的《黑神话&#xff1a;悟空》&#xff0c;凭借炫酷逼真的3D效果和独特…

wordpress 页面URL自动跳转到图片地址?

比如你打开关于我们页面&#xff1a; yourdomain.com/about-us/ 结果自动跳转到了&#xff1a; yourdomain.com/wp-content/uploads/2024/08/about-us.jpg 刚开始以为是不是哪里设置了自动跳转&#xff0c;比如YOAST SEO里&#xff0c;但是结果发现不是。 结果发现&#x…