使用Kotlin实现文字渐变TextView

实现效果:

使用Kotlin实现文字渐变TextView

实现代码:

import android.content.Context
import android.graphics.*
import android.support.annotation.ColorInt
import android.support.annotation.ColorRes
import android.text.TextPaint
import android.util.AttributeSet
import android.widget.TextView
import com.ans.utilactivity.R


class GradientTextView @JvmOverloads constructor(
    context: Context?,
    attrs: AttributeSet? = null
) : TextView(context, attrs) {


    private var mPaint: TextPaint? = null
    private var mLinearGradient: LinearGradient? = null
    private var mMeasureWidth = 0
    private var mTextMatrix: Matrix? = null

    @ColorInt
    private var mStartColor: Int = 0xFF333333.toInt()
    @ColorInt
    private var mEndColor: Int = 0xFF333333.toInt()

    init {
        if (attrs != null) {
            val attrArray = getContext().obtainStyledAttributes(attrs, R.styleable.GradientTextView)
            mStartColor = attrArray.getColor(R.styleable.GradientTextView_startColor, mStartColor)
            mEndColor = attrArray.getColor(R.styleable.GradientTextView_endColor, mEndColor)
        }
    }

    /**
     * 复写onSizeChanged方法
     *
     */
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mMeasureWidth = measuredWidth
        if (mMeasureWidth > 0) {
            mPaint = paint
            //(x0,y0):渐变起始点坐标
            //(x1,y1):渐变结束点坐标
            //color0:渐变开始点颜色,16进制的颜色表示,必须要带有透明度
            //color1:渐变结束颜色
            //colors:渐变数组
            //positions:位置数组,position的取值范围[0,1],作用是指定某个位置的颜色值,如果传null,渐变就线性变化。
            //tile:用于指定控件区域大于指定的渐变区域时,空白区域的颜色填充方法。
            mLinearGradient = LinearGradient(
                0f
                , 0f
                , mMeasureWidth.toFloat()
                , 0f
                , intArrayOf(mStartColor, mEndColor)
                , null
                , Shader.TileMode.CLAMP
            )
            mPaint?.shader = mLinearGradient
            mTextMatrix = Matrix()
        }
    }
}

attr.xml 引用

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

引用:

<前缀.GradientTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:startColor="@color/colorPrimary"
        app:endColor="@color/colorAccent"
       />

 有问题麻烦各位大佬指正。谢谢!

上一篇:Android Studio实现最简单走马灯


下一篇:android中NavigationView(导航抽屉)