本文共 3345 字,大约阅读时间需要 11 分钟。
确认一下是否是你要找的效果呢?如果确定,那就继续阅读吧,或者可以参考下面的一篇文章。
该功能实现非常简单,下面是流程:
1、首先对每个单词进行拆分,即一个字符串拆分成多个字符,对每个字符定义一个Text; 2、对字符的颜色进行定义,并且绑定一个变量值 3、定义一个Timer,并且实时刷新颜色对应的变量值。Text { id: name anchors.left: parent.left height: 10 width: 30 text: qsTr("H") font.pointSize: 30 font.bold: true color: Qt.hsva((15 - (((idx + 3) > 15) ? idx - 12:idx + 3)) * 16/255, 1, 1,1);}Text { id: name1 anchors.left: name.right height: 10 width: 30 text: qsTr("E") font.pointSize: 30 font.bold: true color: Qt.hsva((15 - (((idx + 2) > 15) ? idx - 13:idx + 2)) * 16/255, 1, 1,1);}Text { id: name2 anchors.left: name1.right height: 10 width: 30 text: qsTr("R") font.pointSize: 30 font.bold: true color: Qt.hsva((15 - (((idx + 1) > 15) ? idx - 14:idx + 1)) * 16/255, 1, 1,1);}Text { id: name3 anchors.left: name2.right height: 10 width: 30 text: qsTr("O") font.pointSize: 30 font.bold: true color: Qt.hsva((15 - idx) * 16/255, 1, 1,1);}
上面定义了四个text对象,每个包含一个字母,通过color将idx绑定,idx是从1-15进行循环的,因此有15个颜色进行变换,不同的idx值对应了不同的颜色值。要想实现渐变效果,四个字幕的颜色必须是相邻的,代码中给出四个字母的颜色下标对应的是
[idx + 3, idx + 2, idx + 1, idx ] 由于一共15个颜色,需要对计算后的下标对15进行取余,实现循环变换颜色。Timer { id:timer interval: 100 running: true repeat: true onTriggered: { if (idx + 1 < 15) { idx += 1; } else { idx = 0; } console.log((15 - idx) * 16) }}
定时器是颜色渐变的核心,间隔为100ms,默认启动,并且重复运行,定时器响应函数很简单,对idx进行递增即可。
import QtQuick 2.12import QtQuick.Window 2.12import QtQml 2.12Window { visible: true width: 640 height: 480 title: qsTr("Hello World") property int idx: 10 Rectangle { anchors.centerIn: parent width: 100 height: 60 Text { id: name anchors.left: parent.left height: 10 width: 30 text: qsTr("H") font.pointSize: 30 font.bold: true color: Qt.hsva((15 - (((idx + 3) > 15) ? idx - 12:idx + 3)) * 16/255, 1, 1,1); } Text { id: name1 anchors.left: name.right height: 10 width: 30 text: qsTr("E") font.pointSize: 30 font.bold: true color: Qt.hsva((15 - (((idx + 2) > 15) ? idx - 13:idx + 2)) * 16/255, 1, 1,1); } Text { id: name2 anchors.left: name1.right height: 10 width: 30 text: qsTr("R") font.pointSize: 30 font.bold: true color: Qt.hsva((15 - (((idx + 1) > 15) ? idx - 14:idx + 1)) * 16/255, 1, 1,1); } Text { id: name3 anchors.left: name2.right height: 10 width: 30 text: qsTr("O") font.pointSize: 30 font.bold: true color: Qt.hsva((15 - idx) * 16/255, 1, 1,1); } } Timer { id:timer interval: 100 running: true repeat: true onTriggered: { if (idx + 1 < 15) { idx += 1; } else { idx = 0; } console.log((15 - idx) * 16) } } Component.onCompleted: { timer.start(); }}
如果大家有更好的实现方法,欢迎评论区留言,谢谢。
转载地址:http://nxuun.baihongyu.com/