使用Kotlin语言为Android Studio中的文本设置渐变颜色 [英] Set gradient color for text in Android Studio with Kotlin language
本文介绍了使用Kotlin语言为Android Studio中的文本设置渐变颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文本,我想将渐变颜色设置为其前景.我可以用XML做到吗?
I have a text and I want to set a gradient color as its foreground. May I do it in XML?
还是我应该在一项活动中这样做?我正在用Android Studio中的Kotlin编程.
Or should I do it in an activity? I am programming with Kotlin in Android Studio.
<androidx.constraintlayout.widget.ConstraintLayout xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:gravity="center"
android:text="Text Color is Gradient"
android:textColor="#000"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
文件gradient.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<gradient
android:angle="90"
android:centerColor="#555994"
android:endColor="#b5b6d2"
android:startColor="#555994"
android:type="linear" />
<corners
android:radius="0dp"/>
</shape>
我的活动是这样
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
推荐答案
为了将渐变设置为Textview
文本颜色,必须将textshader
与解析渐变颜色一起使用.您可以根据需要自定义颜色.
In order to set the gradient as Textview
text color, you have to use textshader
with parsing gradients color. You can customise the colors as of your requirement.
val paint = textView.paint
val width = paint.measureText(textView.text.toString())
val textShader: Shader = LinearGradient(0f, 0f, width, textView.textSize, intArrayOf(
Color.parseColor("#F97C3C"),
Color.parseColor("#FDB54E"),
/*Color.parseColor("#64B678"),
Color.parseColor("#478AEA"),*/
Color.parseColor("#8446CC")
), null, Shader.TileMode.REPEAT)
textView.paint.setShader(textShader)
这篇关于使用Kotlin语言为Android Studio中的文本设置渐变颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文