自定義控件-字體顏色切換

1.分解步驟

  • 1.分析效果
  • 2.確定自定義屬性中燥,編寫(xiě)attrs.xml
  • 3.在布局中使用
  • 4.編寫(xiě)自定義控件實(shí)現(xiàn)類(lèi)
  • 5.定義并初始化所需變量(如文字畫(huà)筆,顏色進(jìn)度占比等)
  • 5.ondraw()畫(huà)文字斧蜕,編寫(xiě)繪制邏輯(主要運(yùn)用到“切割畫(huà)板”的思想)
  • 6.其他處理(動(dòng)畫(huà)效果)

2.具體步驟

  • attrs.xml文件 定義需要的控件內(nèi)部屬性變量
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ColorTrackTextView">
    <attr name="originColor" format="color"/>//初始顏色
    <attr name="changeColor" format="color"/>//切換顏色
</declare-styleable>
</resources>
  • 在layout布局中使用
<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
<com.incall.apps.textswitch.ColorTrackTextView
    android:id="@+id/text_draw"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="32sp"
    android:layout_gravity="center"
    app:originColor="@color/black"
    app:changeColor="@color/teal_200"
    android:text="Hello World !!"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="左到右"
        android:layout_gravity="center"
        android:onClick="leftToRight"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="右到右"
        android:layout_gravity="center"
        android:onClick="rightToLeft"/>

</LinearLayout>
  • 編寫(xiě)控件類(lèi)ColorTrackTextView,繼承textView
package com.incall.apps.textswitch;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;

import androidx.annotation.Nullable;
@SuppressLint("AppCompatCustomView")
public class ColorTrackTextView extends TextView {

    private Paint mOriginPaint; //初始顏色畫(huà)筆
    private Paint mChangePaint; //變化顏色畫(huà)筆
    //設(shè)置變色百分比
    private float currentProgress = 0.0f;
    //設(shè)置變色朝向
    Direction mdirection = Direction.LEFT_TO_RIGHT;

    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) {
        this(context, attrs, defStyleAttr, 0);
    }

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

    /**
     * 初始化
     */
    private void initPaint(Context context, AttributeSet attrs) {
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ColorTrackTextView);
        int orginColor = array.getColor(R.styleable.ColorTrackTextView_originColor, getTextColors().getDefaultColor());
        int changeColor = array.getColor(R.styleable.ColorTrackTextView_changeColor, getTextColors().getDefaultColor());
        mOriginPaint = getPaintByColor(orginColor);
        mChangePaint = getPaintByColor(changeColor);
        array.recycle();
    }

    /**
     * 根據(jù)顏色值獲取畫(huà)筆
     *
     * @return
     */
    private Paint getPaintByColor(int color) {
        Paint paint = new Paint();
        //設(shè)置顏色
        paint.setColor(color);
        //抗鋸齒
        paint.setAntiAlias(true);
        //防抖動(dòng)
        paint.setDither(true);
        //設(shè)置字體大小
        paint.setTextSize(getTextSize());
        return paint;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int middle = (int) (currentProgress * getWidth());
        //從左變到右
        if (mdirection == Direction.LEFT_TO_RIGHT) {
            drawText(canvas, mOriginPaint, middle, getWidth());
            drawText(canvas, mChangePaint, 0, middle);
        }
        //從右邊變到左
        else if (mdirection == Direction.RIGHT_TO_LEFT) {
            drawText(canvas, mOriginPaint, 0, getWidth() - middle);
            drawText(canvas, mChangePaint, getWidth() - middle, getWidth());
        }
    }

    /**
     * * @description 文字圖像繪制
     * @param canvas
     * @param paint
     * @param start
     * @param end
     * @return void
     */
    private void drawText(Canvas canvas, Paint paint, int start, int end) {
        canvas.save();//保存畫(huà)板
        //根據(jù)進(jìn)度計(jì)算中間值
        Rect rect = new Rect(start, 0, end, getHeight());
        canvas.clipRect(rect);
        String text = getText().toString();
        //計(jì)算起始位置
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        int x = getWidth() / 2 - bounds.width() / 2;
        //計(jì)算基線
        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();//釋放畫(huà)板
    }

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

    public void setMdirection(Direction mdirection) {
        this.mdirection = mdirection;
    }
}
  • 編寫(xiě)MainActivity,添加屬性動(dòng)畫(huà)君旦,添加按鈕邏輯
package com.incall.apps.textswitch;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    ColorTrackTextView textDraw;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textDraw = findViewById(R.id.text_draw);
    }

    public void leftToRight(View view) {
        textDraw.setMdirection(ColorTrackTextView.Direction.LEFT_TO_RIGHT);
        ValueAnimator valueAnimator = ObjectAnimator.ofFloat(0, 1);
        valueAnimator.setDuration(2000);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float currentProgress = (Float) animation.getAnimatedValue();
                textDraw.setCurrentProgress(currentProgress);
            }
        });
        valueAnimator.start();
    }

    public void rightToLeft(View view) {
        textDraw.setMdirection(ColorTrackTextView.Direction.RIGHT_TO_LEFT);
        ValueAnimator valueAnimator = ObjectAnimator.ofFloat(0, 1);
        valueAnimator.setDuration(2000);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float currentProgress = (Float) animation.getAnimatedValue();
                textDraw.setCurrentProgress(currentProgress);
            }
        });
        valueAnimator.start();
    }
}

3.效果圖

文字顏色轉(zhuǎn)換.gif
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末江场,一起剝皮案震驚了整個(gè)濱河市纺酸,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌址否,老刑警劉巖餐蔬,帶你破解...
    沈念sama閱讀 217,277評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡樊诺,警方通過(guò)查閱死者的電腦和手機(jī)仗考,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)词爬,“玉大人秃嗜,你說(shuō)我怎么就攤上這事《倥颍” “怎么了痪寻?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,624評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)虽惭。 經(jīng)常有香客問(wèn)我橡类,道長(zhǎng),這世上最難降的妖魔是什么芽唇? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,356評(píng)論 1 293
  • 正文 為了忘掉前任顾画,我火速辦了婚禮,結(jié)果婚禮上匆笤,老公的妹妹穿的比我還像新娘研侣。我一直安慰自己,他們只是感情好炮捧,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布庶诡。 她就那樣靜靜地躺著,像睡著了一般咆课。 火紅的嫁衣襯著肌膚如雪末誓。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,292評(píng)論 1 301
  • 那天书蚪,我揣著相機(jī)與錄音喇澡,去河邊找鬼。 笑死殊校,一個(gè)胖子當(dāng)著我的面吹牛晴玖,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播为流,決...
    沈念sama閱讀 40,135評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼呕屎,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了敬察?” 一聲冷哼從身側(cè)響起秀睛,我...
    開(kāi)封第一講書(shū)人閱讀 38,992評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎静汤,沒(méi)想到半個(gè)月后琅催,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,429評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡虫给,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評(píng)論 3 334
  • 正文 我和宋清朗相戀三年藤抡,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片抹估。...
    茶點(diǎn)故事閱讀 39,785評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡缠黍,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出药蜻,到底是詐尸還是另有隱情瓷式,我是刑警寧澤,帶...
    沈念sama閱讀 35,492評(píng)論 5 345
  • 正文 年R本政府宣布语泽,位于F島的核電站贸典,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏踱卵。R本人自食惡果不足惜廊驼,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望惋砂。 院中可真熱鬧妒挎,春花似錦、人聲如沸西饵。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,723評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)眷柔。三九已至期虾,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間驯嘱,已是汗流浹背彻消。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,858評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留宙拉,地道東北人宾尚。 一個(gè)月前我還...
    沈念sama閱讀 47,891評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像谢澈,于是被迫代替她去往敵國(guó)和親煌贴。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容