0
\$\begingroup\$

I have a game that should draw many shapes on the canvas and in every frame these shapes position will change, the game is running smooth but after adding more shapes some jerk arise and it drops some of frames. And this is just happening in high-density devices (more than 320 dpi).

public void run() {
    while (mRunning) {
        if (mSurfaceHolder.getSurface().isValid()) {

            synchronized (mSurfaceHolder){
                canvas = mSurfaceHolder.lockCanvas();


                canvas.drawColor(Color.BLACK);
                drawOnCanvas(canvas);

                mSurfaceHolder.unlockCanvasAndPost(canvas);
            }
        }
    }
}

draw function

public void drawOnCanvas(Canvas canvas) {
    new Thread(changeGamePosRunnable).start();

    for (int i = 0; i < obstacles.size(); i++) {
        Obstacle obstacle = obstacles.get(i);
        x= obstacle.getX();
        y=obstacle.getY();

        canvas.drawLine(0, 0, x, y, linePaint);
        canvas.drawBitmap(bitmap,x,y,null);
    }
}

I have created bitmaps in the constructor, initializing all variables out of the game loop, using SurfaceView and implements Runnable, added Thread.sleep(5); to while loop, tried to decrease bitmap size to about 240 bytes, tried to draw circle instead of bitmap again no change.

It's so strange that the drawing function is so slow in high-density devices, I tried to use some bitmaps as buffer and use them in 3 threads but the game sometimes draw on the wrong location. also I think drawing on another bitmap is not a right solution.

How can I speed things up? The quality does not matter, I just need some more speed.

\$\endgroup\$
1
\$\begingroup\$

You are drawing using the cpu to write pixel per pixel. Instead go hardware accelerated by using opengl or vulkan.

That will allow you to use the gpu which is optimized for drawing stuff that ends up on screen.

\$\endgroup\$
  • \$\begingroup\$ thanks then I should go to learn Open Gl, where can I get a fast Tutorial how to use Open GL in android. \$\endgroup\$ – Afshin Izadi Sep 8 '18 at 9:29
  • 1
    \$\begingroup\$ @AfshinIzadi That's a question for a search engine. Type "opengl android tutorial" into your favourite search tool and you'll get many results. Deciding which result is best for your specific needs is a judgement call you'll need to make. \$\endgroup\$ – DMGregory Oct 19 '18 at 18:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.