1
嗨我目前正試圖創建一個程序,將光標從一個給定的點移動到另一個平滑的隨機運動。我目前使用CoreGraphics創建了以下內容,但它的運行非常不穩定。有想法該怎麼解決這個嗎?非常感激。我把我的Mac OS X應用程序內部的applicationDidFinishLaunching開始執行以下操作:模擬人類鼠標移動
var pos = NSEvent.mouseLocation()
pos.y = NSScreen.mainScreen()!.frame.height - pos.y
moveMouse(CGPoint(x:200,y:200), from: pos)
而這些是我所創建的功能:
func transMouse(point:CGPoint) {
let move = CGEventCreateMouseEvent(nil, CGEventType.MouseMoved, point, CGMouseButton.Left)
CGEventPost(CGEventTapLocation.CGHIDEventTap, move)
}
func moveMouseOne(direction:Character, _ currentPos:CGPoint) -> CGPoint {
var newPos = currentPos
if direction == "r" {
newPos.x = currentPos.x + 1
} else if direction == "l" {
newPos.x = currentPos.x - 1
} else if direction == "u" {
newPos.y = currentPos.y - 1
} else if direction == "d" {
newPos.y = currentPos.y + 1
}
transMouse(newPos)
return newPos
}
func moveMouse(to:CGPoint, from:CGPoint) -> CGPoint {
let dx:Int = Int(to.x - from.x)
let dy:Int = Int(to.y - from.y)
var moves = Array<Character>()
if dx > 0 {
for _ in 0..<dx {
moves.append("r")
}
} else {
for _ in 0..<(-dx) {
moves.append("l")
}
}
if dy > 0 {
for _ in 0..<dy {
moves.append("d")
}
} else {
for _ in 0..<(-dy) {
moves.append("u")
}
}
var pos = from
let delay:Double = 0.0008
let startTime = DISPATCH_TIME_NOW
for var i = 0; i < moves.count; ++i {
let time = dispatch_time(startTime, Int64(delay * Double(i) * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue()) {
let count = moves.count
let random = Int(arc4random_uniform(UInt32(count)))
pos = self.moveMouseOne(moves[random], pos)
if random == count - 1 {
moves.popLast()
} else {
moves[random] = moves.popLast()!
}
}
}
return to
}
我不知道怎樣才能操作使用CoreAnimation,你能解釋一些鼠標? –
也許我誤解了 - 你想以編程方式移動實際的鼠標光標嗎?還是你想要移動別的東西? – dijipiji
是的,我想移動實際的鼠標光標。但據我所見,這不是核心動畫能做的事嗎? –