实现效果:
实现代码:
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" />
到此这篇关于使用kotlin实现文字渐变textview的文章就介绍到这了,更多相关kotlin文字渐变textview内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!
如对本文有疑问, 点击进行留言回复!!
Codeforces C. A Cookie for You (模拟 / 分类 / 贪心) (Round #654 Div.2)
DialogFragment弹窗(带黑色透明背景和不带黑色透明背景)
android 常用布局文件(LinearLayout,RelativeLayout,FrameLayout,ConstraintLayout,TableLayout)
网友评论