本文介绍了使用 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 中设置文本的渐变颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!