这篇文章主要介绍了使用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"
/>
到此这篇关于使用Kotlin实现文字渐变TextView的文章就介绍到这了,更多相关Kotlin文字渐变TextView内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
织梦狗教程
本文标题为:使用Kotlin实现文字渐变TextView的代码


基础教程推荐
猜你喜欢
- IOS应用内跳转系统设置相关界面的方法 2022-11-20
- android studio按钮监听的5种方法实例详解 2023-01-12
- Flutter手势密码的实现示例(附demo) 2023-04-11
- iOS开发教程之XLForm的基本使用方法 2023-05-01
- Flutter绘图组件之CustomPaint使用详解 2023-05-12
- Android开发使用RecyclerView添加点击事件实例详解 2023-06-15
- Android中的webview监听每次URL变化实例 2023-01-23
- Android多返回栈技术 2023-04-15
- 解决Android Studio突然不显示logcat日志的问题 2023-02-04
- IOS 播放系统提示音使用总结(AudioToolbox) 2023-03-01