有没有更好的方法来制作可拖动的背景?
我正在开始一个新项目,到目前为止,我已经制作了一个简单的应用程序,其中有一个绘制在 Canvas
上的图像,您可以用手指在屏幕上拖动该图像。这个想法是在游戏的 Canvas
上绘制大量内容。然而,拖动速度非常缓慢,用手指拖动时,屏幕可能每秒更新图像 2-3 次。它的速度非常慢,所以我假设我做错了(我使用的是 Nexus S)。
我只有应用程序的基本框架,只有一个 SurfaceView,其中包含一个线程,用于使用这一张图像更新 Canvas。这是代码:
// In GameThread
private void doDraw(Canvas c) {
if(canvasInit){
Bitmap background = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.bg);
c.drawBitmap(background, offsetX, offsetY, null);
}
}
public boolean doTouchDown(MotionEvent event) {
if(drag == false){
//initialize drag
startX = event.getX();
startY = event.getY();
drag = true;
}else{
//caluclate new position
offsetX = Math.max(Math.min(0, offsetX + (event.getX() - startX)), mCanvasWidth - BACKGROUND_WIDTH);
offsetY = Math.max(Math.min(0, offsetY + (event.getY() - startY)), mCanvasHeight- BACKGROUND_HEIGHT);
startX = event.getX();
startY = event.getY();
}
return true;
}
public boolean doTouchUp(MotionEvent event){
drag = false;
return true;
}
I'm starting out a new project, and thus far I've made a simple app that has an image which is drawn onto a Canvas
, which you can drag around the screen with your finger. The idea is to draw lots of stuff onto this Canvas
for a game. However the dragging is extremely laggy, while dragging with my finger the screen updates the image maybe 2-3 times a second. It's very noticeably slow, so I'm assuming I'm doing it very wrong (I'm on a Nexus S).
I only have the very barebones of the app, just a SurfaceView containing a thread to update the Canvas
with this one image. Here's the code:
// In GameThread
private void doDraw(Canvas c) {
if(canvasInit){
Bitmap background = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.bg);
c.drawBitmap(background, offsetX, offsetY, null);
}
}
public boolean doTouchDown(MotionEvent event) {
if(drag == false){
//initialize drag
startX = event.getX();
startY = event.getY();
drag = true;
}else{
//caluclate new position
offsetX = Math.max(Math.min(0, offsetX + (event.getX() - startX)), mCanvasWidth - BACKGROUND_WIDTH);
offsetY = Math.max(Math.min(0, offsetY + (event.getY() - startY)), mCanvasHeight- BACKGROUND_HEIGHT);
startX = event.getX();
startY = event.getY();
}
return true;
}
public boolean doTouchUp(MotionEvent event){
drag = false;
return true;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您似乎每次绘制时都会加载位图。您可以尝试将资源加载移动到某种初始化方法/ SurfaceView 构造函数并比较性能?
You seem to be loading the Bitmap every time you draw. You can try moving the resource loading to some kind of initialisation method/ SurfaceView constructor and compare the performance?
我认为问题出在
doDraw
方法中,您每次Draw
创建一个新的位图,尝试在构造函数
中加载此Bitmap
code> 然后在 doDraw 方法中获取它的引用,并使用您的 x 和 y 绘制它。I Think the problem is in
doDraw
method, your creating a new Bitmap everyDraw
, try to load thisBitmap
inConstructor
then get it reference indoDraw
method, and draw it using your x and y.