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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ht.lineargradienttv.MainActivity">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="你有多久单身一人不再去旅行"
android:textSize="18sp"
app:showStyle="UNIDIRECTION"
app:showTime="40"
app:tvColor="#f54b4b" />
code:
/** * Package com.ht.lineargradienttv * Created by HT on 2018/7/3. */ public class LinearGradientTv extends AppCompatTextView { private TextPaint paint; private LinearGradient linearGradient; private Matrix matrix; private float translateX; private float deltaX = 26; private int showTime;//显示的时间 private int showStyle; public static final int UNIDIRECTION = 0; public static final int LOOP = 1; private int color; public LinearGradientTv(Context context, AttributeSet attrs) { super(context, attrs); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.LinearGradientTextView); showTime = typedArray.getInteger(R.styleable.LinearGradientTextView_showTime, 40); showStyle = typedArray.getInt(R.styleable.LinearGradientTextView_showStyle, UNIDIRECTION); color = typedArray.getColor(R.styleable.LinearGradientTextView_tvColor, Color.RED); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); paint = getPaint(); String text = getText().toString(); float textWidth = paint.measureText(text); //GradientSize三个文字的大小 int gradientSize = (int) (3 * textWidth / text.length()); //边缘融合 linearGradient = new LinearGradient(-gradientSize, 0, gradientSize, 0, new int[]{Color.YELLOW, color, Color.YELLOW}, new float[]{0, 0.5f, 1}, Shader.TileMode.CLAMP); paint.setShader(linearGradient); matrix = new Matrix();//Matrix表示变换矩阵 } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); float textWidth = (getPaint().measureText(getText().toString())); translateX += deltaX; switch (showStyle) { case UNIDIRECTION: //单向闪动 if (translateX > textWidth + 1 || translateX < 1) { translateX = 0; translateX += deltaX; } break; case LOOP: //来回闪动 if (translateX > textWidth + 1 || translateX < 1) { deltaX = -deltaX; } break; } matrix.setTranslate(translateX, 0);//平移,两个参数分别为x和y方向平移量 linearGradient.setLocalMatrix(matrix);//渐变的平移矩阵(setLocalMatrix方法是Shader类的方法) postInvalidateDelayed(showTime);//延迟重绘(刷新) } }
没什么难度,效果完成!主要是一些自定义 view 的基础。