Android 渐变色TextView

Android 渐变色TextView


利用shader来实现

在代码中设置:

       TextView mText = (TextView) findViewById(R.id.text);
        LinearGradient mLinearGradient = new LinearGradient(0, 0, 0, mText.getPaint().getTextSize(),
               getResources().getColor(android.R.color.white)
                , getResources().getColor(android.R.color.black),
                Shader.TileMode.CLAMP
        );
        mText.getPaint().setShader(mLinearGradient);

自定义控件:

package com.baidu.location.textviewtest;
 
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.widget.TextView;
 
/**
 * Created by hanbo on 2018-01-05.
 */
 
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, getWidth(), 0,
                    StringToColor("#4ef1ff"), StringToColor("#0e9aeb"),
                    Shader.TileMode.CLAMP));
        }
    }
 
    /**
     * #颜色转16进制颜色
     * @param str {String} 颜色
     * @return
     */
    private  int StringToColor(String str) {
        return 0xff000000 | Integer.parseInt(str.substring(2), 16);
    }
}

前端引用

<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.baidu.location.textviewtest.GradientTextView
        android:id="@+id/text"
        android:text="Helloworld"
        android:textSize="20sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Android 渐变色TextView_第1张图片

你可能感兴趣的:(不止代码codelife,android)