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;
}
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?