目录
1、效果
2、核心
按照圆形运动,主要用到以下函数:
var angle = Math.PI * currentValue / 50.0;
var a1 = Math.cos(angle) * win.width/2;
var b1 = Math.sin(angle) * win.width/2;
这里面angle是旋转角度,currentValue是0到100的数值,win.width/2是半径,a1和b1是x,y。
3、源代码
代码粘到下面:
import QtQuick 2.4
import QtQuick.Window 2.2
Window {
id:win
visible: true
width: 400
height: 400
property real currentValue : 0;
Rectangle {
width: parent.width/2
height: width
x: parent.width/4
y: parent.width/4
radius: width/2
color:"yellow"
}
Rectangle {
id: ball1
width: 50
height: width
radius: width/2
x:parent.width - width/2
y:parent.height/2 - height/2
color: "green"
}
Rectangle {
id: ball2
width: 40
height: width
radius: width/2
x:parent.width/4*3 - width/2
y:parent.height/2 - height/2
color:Qt.rgba(0.5,0.5,0.5,0.5)
}
Text {
id: txt
anchors.centerIn: parent
font.pixelSize: parent.width/5
color: "blue"
text: "0%";
}
Timer{
id: timer
interval: 50;
running: true;
repeat: true;
onTriggered: {
if(currentValue == 100) {
currentValue = 0;
}
currentValue += 1;
txt.text = currentValue.toString()+"%";
var angle = Math.PI * currentValue / 50.0;
var a1 = Math.cos(angle) * win.width/2;
var b1 = Math.sin(angle) * win.width/2;
var a2 = Math.cos(angle) * win.width/4;
var b2 = Math.sin(angle) * win.width/4;
ball1.x = win.width/2-ball1.width/2 + a1
ball1.y = win.height/2-ball1.width/2 + b1
ball2.x = win.width/2-ball2.width/2 + a2
ball2.y = win.height/2-ball2.width/2 + b2
}
}
}
4、Math
在QML中,各种数学运算使用JavaScript中的Math,其中包含很多常用函数,如下:
返回一组数中的最大数
console.log(Math.max(1,3,4,5,-1)); // 5
返回一组数中的最小数
console.log(Math.min(1,3,4,5,-1)); // -1
对一个数向上舍入
console.log(Math.ceil(0.95)); // 1
console.log(Math.ceil(-1.9)); // -1
console.log(Math.ceil(1.9)); // 2
console.log(Math.ceil(1.3)); // 2
对一个数下舍入
console.log(Math.floor(0.95)); // 0
console.log(Math.floor(-1.9)); // -2
console.log(Math.floor(1.9)); // 1
console.log(Math.floor(1.3)); // 1
四舍五入
console.log(Math.round(0.95)); // 1
console.log(Math.round(-1.9)); // -2
console.log(Math.round(1.9)); // 2
console.log(Math.round(1.3)); // 1
console.log(Math.round(0.5)); // 1
console.log(Math.round(-0.5)); // 0
console.log(Math.round(1.5)); // 2
console.log(Math.round(-1.5)); // -1
随机数 radom()返回[0.0,1.0)之间的小数,不包含1
let a = Math.random()*10+1;
console.log(a); // 1-10之间的随机数
console.log(Math.floor(Math.random()*10)); //[0,9]之间的随机数
5、进一步说明Math
Math 对象用来执行数学运算,它有点儿特别,你不用使用 new 运算符构造对象,可以直接使用。使用 Math 对象的代码片段:
var pi = Math.PI
var textColor = Qt.rgba(Math.random(), Math.random(), Math.random())
Math 有下列方法:
- max(x, y),返回 x 和 y 中的最大值。
- min(x, y),返回 x 和 y 中的最小值。
- abs(x),返回数的绝对值。
- sqrt(x),返回数的平方根。
- pow(x, y),返回 x 的 y 次幕。
- random(),返回 0〜1 之间的随机数。
- sin(x),返回数的正弦值。
- asin(x),返回数的反正弦值。
- exp(x),返回 e 的指数。
- log(x),返回数的自然对数(底为 e)。
- valueOf(),返回 Math 对象的原始值。