自定义View
// 定义一个自定义的TextView类,继承自TextViewpublic class GradientTextView extends TextView { // 定义两个颜色变量,分别表示颜色A和颜色B private int startColor; private int endColor; // 定义一个构造方法,接收一个Context对象和一个AttributeSet对象 public GradientTextView(Context context, AttributeSet attrs) { super(context, attrs); // 从AttributeSet对象中获取自定义的属性值 TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.GradientTextView); startColor = typedArray.getColor(R.styleable.GradientTextView_startColor, Color.BLACK); endColor = typedArray.getColor(R.styleable.GradientTextView_endColor, Color.WHITE); typedArray.recycle(); } // 重写onDraw方法,绘制渐变的文字 @Override protected void onDraw(Canvas canvas) { // 获取TextView的宽度和高度 int width = getMeasuredWidth(); int height = getMeasuredHeight(); // 创建一个LinearGradient对象,指定渐变的方向和颜色 LinearGradient linearGradient = new LinearGradient(0, 0, 0, height, startColor, endColor, Shader.TileMode.CLAMP); // 获取TextView的Paint对象,并设置渐变的Shader Paint paint = getPaint(); paint.setShader(linearGradient); // 调用父类的onDraw方法,绘制文字 super.onDraw(canvas); }}
声明属性
<?xml version="1.0" encoding="utf-8"?><resources> <declare-styleable name="GradientTextView"> <attr name="startColor" format="color" /> <attr name="endColor" format="color" /> </declare-styleable></resources>
使用
<com.example.GradientTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:startColor="#FF0000" app:endColor="#00FF00" />
最后一次更新于November 4th, 2023