栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

使用Kotlin实现文字渐变TextView的代码

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用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)
    }
  }

  
  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 引用


  
  

引用:

<前缀.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内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/154139.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号