TextView tv = findViewById(R.id.custom_text);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/gillsans.ttf");
tv.setTypeface(tf);
// 線性漸變 Shader:從左到右,三色過渡
Shader shader = new LinearGradient(
0, 0, tv.getPaint().measureText(tv.getText().toString()), tv.getTextSize(),
new int[]{Color.parseColor("#B4E391"), Color.parseColor("#61C419"), Color.parseColor("#B4E391")},
new float[]{0, 0.5f, 1},
Shader.TileMode.MIRROR
);
tv.getPaint().setShader(shader);
<TextView
android:id="@+id/custom_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="99%"
android:textSize="25sp"
android:shadowColor="#67587686"
android:shadowDx="5"
android:shadowDy="5"
android:shadowRadius="3"
android:gravity="center" />
Shader 負責文字填充顏色(漸變、圖片紋理等),shadow* 屬性負責描邊/投影效果,兩者疊加產生立體感。
getPaint().measureText() 需在佈局完成後調用(如 onWindowFocusChanged 或 ViewTreeObserver),否則寬度為 0。assets/fonts/ 目錄。