从 Android Canvas 获取像素值
我目前正在使用 SurfaceView 编写 Android 游戏。我已经尽可能地优化了游戏,并且运行起来非常流畅。但是,我合并了碰撞检测,这有点混乱。我想通过直接从画布读取像素来进行碰撞检测。这可以吗?我发现的最接近的方法是使用 setBitmap 将新位图附加到画布。然后,当我绘制到画布上时,位图将会更新。这是要走的路吗?谢谢。
I'm currently writing an Android game using surfaceView. I've optimized the game as much as possible and it runs quite smoothly. However, I have collision detection incorporated which is a bit messy. I would like to do collision detection by reading pixels directly from the canvas. Is this possible to do? The closest to this that I have found was to attach a new bitmap to the canvas using setBitmap. Then when I drew to the canvas, the bitmap would be updated. Would this be the way to go? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尽管您应该以不同的方式管理碰撞检测,但您可以使用下一行代码获取给定位置上的像素颜色:
mView 是包含画布的视图,mBitmap 是用于创建画布的位图:
Although you should manage the collision detection in a different way, you can get the pixel color on a given position with the next line of code:
mView is the View that contains your canvas and mBitmap is the Bitmap with which you created your canvas:
来自 Canvas API:
因此,您永远不会向画布询问像素数据,因为画布本身并不真正“拥有”像素数据。用于进行绘制调用的画布始终附加到位图(您正在其上绘制的位图),因此该位图是您应该从中获取像素数据的位置。
碰撞检测通常成本高昂,但采用基于位图的流程可能会使情况变得更糟,具体取决于您想要做什么。请注意。
From the Canvas API:
So you wouldn't ever ask a canvas for pixel data, because the canvas itself doesn't really "own" pixel data. The canvas which you use to make draw calls is always attached to a bitmap (the one you're drawing on), so that bitmap is where you should get your pixel data from.
Collision detection is usually costly, but going to a bitmap-based process could make it even worse, depending on what you're trying to do. Just a heads up.
我同意乔希的观点。如果精度在您的应用程序中如此重要,您可能希望将屏幕尺寸/分辨率数据合并到某种物理引擎中。尝试构建完全基于视觉处理的物理引擎可能会花费不必要的成本。
I agree with Josh. If precision is that important in your app, you may want to incorporate screen size/resolution data into some kind of physics engine. Trying to build a physics engine based entirely on visual processing is probably unnecessarily costly.