본문 바로가기

[Android/Kotlin] 안드로이드 Gradient TextView

꿈꾸는블로그왕 2021. 2. 7.

안녕하세요. 오늘은 TextView에 Gradient 효과를 주는 방법에 대해서 알아보겠습니다.

 

아래와 같이 글씨에 Gradient 효과가 들어갑니다.

 

 

 

[LinearGradientSpan.kt]

class LinearGradientSpan(
    private val containingText: String,
    private val textToStyle: String,
    @ColorInt private val startColorInt: Int,
    @ColorInt private val endColorInt: Int
) : CharacterStyle(), UpdateAppearance {

    override fun updateDrawState(tp: TextPaint?) {
        tp ?: return

        var leadingWidth = 0f
        val indexOfTextToStyle = containingText.indexOf(textToStyle)
        if (!containingText.startsWith(textToStyle) && containingText != textToStyle) {
            leadingWidth = tp.measureText(containingText, 0, indexOfTextToStyle)
        }
        val gradientWidth = tp.measureText(containingText, indexOfTextToStyle, 
            indexOfTextToStyle + textToStyle.length)

        tp.shader = LinearGradient(
            leadingWidth,
            0f,
            leadingWidth + gradientWidth,
            0f,
            startColorInt,
            endColorInt,
            Shader.TileMode.REPEAT
        )
    }
}

 

[MainActivity.kt]

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val txtHello: TextView = findViewById(R.id.txt_hello)
        val text = "Hello World!"
        val purple = ContextCompat.getColor(this, R.color.start)
        val teal = ContextCompat.getColor(this, R.color.end)
        val spannable = text.toSpannable()
        spannable[0..text.length] = LinearGradientSpan(text, text, purple, teal)
        txtHello.text = spannable
    }

}

[colors.xml]

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="start">#ff6e7f</color>
    <color name="end">#bfe9ff</color>
</resources>

 

[activity_main.xml]

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txt_hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="60sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.Const

댓글