如何通过CGEvent模拟惯性滚动效果?
实现带缓入缓出动画的CGEvent滚动效果
我希望让应用用户能够通过CGEvent实现带有缓入(ease-in)和缓出(ease-out)动画的滚动效果。目前我已经能通过CGEvent发送滚动事件,下面是用来演示需求的简易Playground代码。
由于找不到实现此功能的简易API,我想到通过多次滚动(至少几十次)并在中间添加延迟的方式来实现。我当然可以提高scrollY函数的精度,但希望能找到更简便、更流畅的实现方式。
extension CGEvent { public class func scrollMouse(onPoint point: CGPoint, xLines: Int, yLines: Int) { if #available(OSX 10.13, *) { guard let scrollEvent = CGEvent(scrollWheelEvent2Source: nil, units: CGScrollEventUnit.line, wheelCount: 2, wheel1: Int32(yLines), wheel2: Int32(xLines), wheel3: 0) else { return } scrollEvent.setIntegerValueField(CGEventField.eventSourceUserData, value: 1) scrollEvent.post(tap: CGEventTapLocation.cghidEventTap) } else { // scroll event is not supported for macOS older than 10.13 } } } func scrollY() { let y = 12 let sleep: UInt32 = 10000 // The ease-IN portion for i in stride(from: 1, to: y, by: 1) { CGEvent.scrollMouse(onPoint: CGPoint.zero, xLines: 0, yLines:-i) usleep(sleep * UInt32(i)) } // The ease-OUT portion for i in stride(from: y, to: 1, by: -1) { CGEvent.scrollMouse(onPoint: CGPoint.zero, xLines: 0, yLines:-i) usleep(sleep * UInt32(y + (y - i))) } }
内容的提问来源于stack exchange,提问作者se_puede_dev
相关产品推荐
相关产品推荐

