1. 程式人生 > 其它 >【CustomView】漸變色文字(GradientTextView)- 簡單實現

【CustomView】漸變色文字(GradientTextView)- 簡單實現

技術標籤:# Custom-viewLinearGradientshader

LinearGradient:用於建立一個沿直線繪製線性漸變的著色器。

/**
 * 建立一個沿直線繪製線性漸變的著色器。
 * @param x0漸變線起點的x座標
 * @param y0漸變線起點的y座標
 * @param x1漸變線末端的x座標
 * @param y1漸變線末端的y座標
 * @param color0漸變線開始處的sRGB顏色。
 * @param color1漸變線末端的sRGB顏色。
 * @param tile著色器平鋪模式( Shader.TileMode:“著色器”拼貼模式此值不能為null )
 **/
public LinearGradient (
                float x0, 
                float y0, 
                float x1,  
                float y1, 
                int color0,
                int color1,
                Shader.TileMode tile
) 

最近在專案中又遇到漸變色文字顯示,有空了就整理一篇文章來實現(LinearGradient),效果如下:

實現很簡單,一行程式碼解決:

paint.shader = LinearGradient(0F, 0F, width, height, colorStart, colorEnd, Shader.TileMode.CLAMP)

#1. 自定義TextView 程式碼:

class GradientTextView @JvmOverloads constructor(
        context: Context, 
        attrs: AttributeSet? = null, 
        defStyleAttr: Int = 0) : AppCompatTextView(context, attrs, defStyleAttr) {

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        if (changed) {
            paint.shader = LinearGradient(0F, 0F, width.toFloat() / 2, height.toFloat(), ContextCompat.getColor(context, R.color.colorMainGradient), ContextCompat.getColor(context, R.color.colorMain), Shader.TileMode.CLAMP)
        }
    }
}
<color name="colorMain">#20C7F2</color>
<color name="colorMainGradient">#50E3C2</color>

#2. XML使用:

<com.android.***.GradientTextView
        android:id="@+id/gradientTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="測試漸變色"
        android:textSize="18sp"
        android:textStyle="bold" />


*** 補充:

如果需要方便設定漸變色的起始和結束色值,我們可以有兩種處理方式:

#1. 給View新增屬性(AttributeSet):

第一步 新增resources屬性:

<declare-styleable name="GradientTextView">
     <attr name="startColor" format="color" />
     <attr name="endColor" format="color" />
</declare-styleable>

第二步 在自定義View中載入屬性,設定色值:

val attributes = context.obtainStyledAttributes(attrs,R.styleable.GradientTextView, 0, 0)
val startColor = attributes.getResourceId(
      R.styleable.GradientTextView_startColor,
      R.color.primary_purple
)
val endColor = attributes.getResourceId(
      R.styleable.GradientTextView_endColor,
      R.color.colorAccent
)

#2. 在自定義的View中新增設定色值的方法:

var startColor: Int = 0
var endColor: Int = 0

fun setGradientColor(startColor: Int, endColor: Int) {
        this.startColor = startColor
        this.endColor = endColor
}
view.setGradientColor(R.color.colorPrimaryDark, R.color.colorPrimary)