使用QtQuick如何製作帶有冷卻效果的按鈕
在很多遊戲裏,一個技能釋放之後,需要一段時間冷卻,然後纔可以繼續使用,在我做的小遊戲《抗戰》中也需要類似的功能,比如炮擊、空襲、補給,那麼在QML中如何實現這個效果呢?
分析一下整個過程:點擊按鈕後,按鈕進入無效狀態,然後背景出現某種冷卻的效果,當冷卻效果結束後,再置按鈕有效。按鈕一般是圓形的,有文字。
簡單分析之後,“如何製作帶有冷卻效果的按鈕”可以分解爲兩個小問題:
1 如果繪製圓形按鈕?
2 如何連續按鈕背景顏色?
1 如何繪製圓形按鈕?
開始還是不習慣QML的編程思路,對着文檔找Button的屬性,找不到任何線索,後來看到了ButtonStyle,在Rectangle類型中有radius,用於繪製圓角矩形,而ButtonStyle可以設置爲Rectangle,將Button的高和寬這是爲相同的值,再將Rectangle::radius設置爲按鈕寬度的一半,這時繪製的按鈕就是圓形的。
2 如何連續按鈕背景顏色?
在Rectangle中有梯度屬性gradient,可以設置背景顏色漸變過程。根據這個屬性,設置三個GradientStop對象A、B、C,A的位置在0.0,顏色”grey”,C的位置在1.0,顏色"#ccc",關鍵就在B,B的顏色與A一致爲”grey”,然後位置由1.0變到0.0,這樣效果就是一個從下往上完成冷卻的效果。
順帶還有一個問題:改爲原型按鈕後,默認字體很小,不好看,這就是第三個問題。
3 如何設置Button字體大小?
還是使用style,使用Text設置ButtonStyle::label屬性,可以改變文字大小。
最終的效果是這樣子的
代碼如下:
// 說明:帶有冷卻效果的按鈕組件
// 作者:陶赫 郵箱:[email protected] ,博客:http://blog.csdn.net/taohe_0
// 時間:20170225
import QtQuick 2.0
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
Button
{
id : buttonSelf
height: width
// 冷卻屬性
property bool chillDown: false
property int chillDownDuration : 3000
style: ButtonStyle
{
label: Text
{
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
font.pointSize: 20
text: control.text
}
// 定義背景,實現冷卻效果
background: Rectangle
{
implicitWidth: 100
implicitHeight: 25
border.width: control.activeFocus ? 2 : 1
border.color: "#888"
// 調整圓角,使按鈕看起來是圓形
radius: width / 2
// 冷卻效果有三個梯度對象實現,兩端固定,中間的GradientStop由1.0端移動到0.0端就能表現出冷卻的過程
gradient: Gradient
{
property double gradientPos: 1.0
GradientStop { position: 0 ; color: control.pressed ? "blue" : "grey"}
GradientStop { id : cdGradient; position: 1.0; color: control.pressed ? "blue" : "grey"}
GradientStop { position: 1 ; color: control.pressed ? "lightblue" : "#ccc"}
}
// 完成"冷卻"過程
PropertyAnimation
{
target: cdGradient
property: "position"
from : 1.0
to : 0.0
duration: chillDownDuration
running: chillDown
// 啓動時,置按鈕無效
onStarted: {buttonSelf.enabled = false}
// 動畫停止時,置按鈕有效,冷卻標誌爲無效
onStopped: {buttonSelf.enabled = true;chillDown=false}
}
}
}
}