IOS開發-UIDynamic(物理模擬)簡單使用,ios-uidynamic

來源:互聯網
上載者:User

IOS開發-UIDynamic(物理模擬)簡單使用,ios-uidynamic

UIDynamic是從IOS7開始引入的一種新技術,隸屬於UIKit架構,我們可以認為是一種物理引擎能類比和模擬現實生活中的物理現象,比如重力,彈性碰撞等。

可以讓開發人員遠離物理公式的情況下,實現一些物理模擬效果。

這裡簡單介紹一下重力,碰撞,捕捉的用法。

先介紹一下使用的大致步驟

  • 建立物理模擬器
  • 建立相應的物理模擬行為
  • 將物理模擬行為添加到物理模擬器

 

一,重力與碰撞

提前在StoryBoard準備兩個UIView,一個紅色,一個藍色。藍色在紅色的下方,保證紅色下落能碰到藍色的view。

 

 1     //建立物理模擬器 2     UIDynamicAnimator *animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view]; 3     self.animator = animator;  //強引用animator,否則代碼塊執行完成後,將被釋放 4      5     //建立重力行為 6     UIGravityBehavior *gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[self.redView]]; 7      8     //設定一些屬性(可以不設定,不設則都為預設) 9     gravityBehavior.gravityDirection = CGVectorMake(0, 1);  //重力方向10     gravityBehavior.angle = M_PI*0.5;  //重力方向11     gravityBehavior.magnitude = 0.5; //重力加速度,1代表加速度是(每秒100個點)12     13     //把重力行為行為添加到模擬器14     [animator addBehavior:gravityBehavior];15     16     17     //建立碰撞行為18     UICollisionBehavior *collisionBehavior = [[UICollisionBehavior alloc] initWithItems:@[self.redView,self.blueView]];19     20     //設定碰撞邊界,不設定就會飛出螢幕,設定就會在螢幕邊框處產生碰撞效果21     collisionBehavior.translatesReferenceBoundsIntoBoundary = YES;22     23     //將碰撞行為加入物理模擬器24     [animator addBehavior:collisionBehavior];

代碼執行後,就能看到紅色的view下落,並撞擊藍色的View了。

 

二,捕捉行為

 1 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 2 { 3     //擷取觸摸點 4     UITouch *touch = [touches anyObject]; 5     CGPoint point = [touch locationInView:touch.view]; 6      7     //建立模擬模擬器 8     UIDynamicAnimator *animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view]; 9     self.animator = animator;  //模擬器10     11     //建立捕捉行為12     UISnapBehavior *snapBehavior = [[UISnapBehavior alloc] initWithItem:self.redView snapToPoint:point];13     14     //設定反彈係數(反彈幅度越大,值越大,反彈幅度越小)15     snapBehavior.damping = 0.5;16     17     //將行為添加到模擬器18     [animator addBehavior:snapBehavior];19     20 }

 運行一下,點擊螢幕,可以發現,紅色的view就很調皮的跟著你的手指移動啦

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.