从 Android Canvas 获取像素值

发布于 2024-09-08 15:44:48 字数 174 浏览 2 评论 0原文

我目前正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

尐偏执 2024-09-15 15:44:48

尽管您应该以不同的方式管理碰撞检测,但您可以使用下一行代码获取给定位置上的像素颜色:

mView.mBitmap.getPixel(j, i)

mView 是包含画布的视图,mBitmap 是用于创建画布的位图:

Canvas mCanvas = new Canvas(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.mBitmap.getPixel(j, i)

mView is the View that contains your canvas and mBitmap is the Bitmap with which you created your canvas:

Canvas mCanvas = new Canvas(mBitmap);
蓝咒 2024-09-15 15:44:48

来自 Canvas API

Canvas 类负责“绘制”
来电。要画东西,你需要 4
基本组件:一个位图来保存
像素,一个用于托管绘图的画布
调用(写入位图),a
绘图基元(例如矩形、路径、
文本、位图)和绘画(以
描述颜色和款式
绘图)。

因此,您永远不会向画布询问像素数据,因为画布本身并不真正“拥有”像素数据。用于进行绘制调用的画布始终附加到位图(您正在其上绘制的位图),因此该位图是您应该从中获取像素数据的位置。

碰撞检测通常成本高昂,但采用基于位图的流程可能会使情况变得更糟,具体取决于您想要做什么。请注意。

From the Canvas API:

The Canvas class holds the "draw"
calls. To draw something, you need 4
basic components: A Bitmap to hold the
pixels, a Canvas to host the draw
calls (writing into the bitmap), a
drawing primitive (e.g. Rect, Path,
text, Bitmap), and a paint (to
describe the colors and styles for the
drawing).

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.

临风闻羌笛 2024-09-15 15:44:48

我同意乔希的观点。如果精度在您的应用程序中如此重要,您可能希望将屏幕尺寸/分辨率数据合并到某种物理引擎中。尝试构建完全基于视觉处理的物理引擎可能会花费不必要的成本。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文