android Textview颜色渐变

时间:2023-02-11 10:23:34

1.在代码中设置:

TextView mText = (TextView) findViewById(R.id.text);
LinearGradient mLinearGradient = new LinearGradient(0, 0, 0, mText.getPaint().getTextSize(), Color.WHITE, Color.BLACK, Shader.TileMode.CLAMP);
mText.getPaint().setShader(mLinearGradient);

2.自定义控件:

package com.leigo.demo.view;

import android.content.Context;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * Created by Administrator on 2014/9/9.
 */
public class GradientTextView extends TextView {

    public GradientTextView(Context context) {
        super(context);
    }

    public GradientTextView(Context context,
                            AttributeSet attrs) {
        super(context, attrs);
    }

    public GradientTextView(Context context,
                            AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onLayout(boolean changed,
                            int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
            getPaint().setShader(new LinearGradient(
                    0, 0, 0, getHeight(),
                    Color.WHITE, Color.BLACK,
                    Shader.TileMode.CLAMP));
        }
    }
}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <com.leigo.demo.view.GradientTextView
        android:id="@+id/text"
        android:text="@string/hello_world"
        android:textSize="20sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


android Textview颜色渐变