简体   繁体   English

Android canvas onDraw计时

[英]android canvas onDraw timing

  1. I am making an Android game in which some graphical elements move fast. 我正在制作一款Android游戏,其中一些图形元素快速移动。 I am going to use Canvas but fear that the onDraw method will be called at irregular interevals making the fast elements move at irregular speeds. 我将使用Canvas,但是担心onDraw方法会在不规则的间隔间被调用,从而使快速元素以不规则的速度运动。 Is there a way to make sure that the onDraw method is called at regular intervals. 有没有一种方法可以确保定期调用onDraw方法。

  2. Alternately if I can get the system time in msec I can take the difference between two consecutive calls to onDraw and based on the speed of these fast elements make the their movement smooth. 或者,如果我可以以毫秒为单位获取系统时间,则可以采用两次连续调用onDraw之间的差值,并基于这些快速元素的速度来使它们的运动平稳。

Kindly help, 请帮助,

Sameer 沙美尔

I am going to use Canvas but fear that the onDraw method will be called at irregular interevals making the fast elements move at irregular speeds 我将使用Canvas,但担心onDraw方法会在不规则的间隔间被调用,从而使快速元素以不规则的速度移动

You should not update the position of objects in onDraw() , because: 应该更新对象中的位置onDraw()这是因为:

  • Indeed, the method might not be called at predefined intervals 确实,该方法可能不会以预定的间隔被调用
  • It is meant to draw objects, not update objects 它旨在绘制对象,而不是更新对象

Instead, update the objects/world in another method that you call at regular intervals using a timer. 而是,使用计时器定期调用的另一种方法来更新对象/世界。

After updating the world, call invalidate() on your View to trigger the onDraw() method. 更新世界之后,在View上调用invalidate()来触发onDraw()方法。 If your application has some spare time it will be called. 如果您的应用程序有空闲时间,它将被调用。 If not, no problem since the world update method will keep on running and thus updating your world. 如果没有, world update method将继续运行,从而更新您的世界,这没有问题。

(Of course, if your application is too busy the view is never updated and you have problems to solve!) (当然,如果你的应用程序是太忙的观点是永远不会更新,您有问题需要解决!)

Alternately if I can get the system time in msec I can take the difference between two consecutive calls to onDraw and based on the speed of these fast elements make the their movement smooth. 或者,如果我可以以毫秒为单位获取系统时间,则可以采用两次连续调用onDraw之间的差值,并基于这些快速元素的速度来使它们的运动平稳。

This is the way to go in the 'world update method'! 这是进入“世界更新方法”的方式! It will correct for the irregular timer intervals. 它将纠正不规则的计时器间隔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM