Canvas中的DrawBitmap很慢

时间:2018-05-28 17:18:36

标签: java android canvas bitmap android-drawable

以下是我的代码

public class GameController extends SurfaceView implements SurfaceHolder.Callback {
        public static int WIDTH =800;
        public static int HEIGHT =399;

        private GameThread gameThread;
        private ArrayList<Background> backgrounds = new ArrayList<>();
        private Bitmap[] bgsrc ;

        public GameController(Context context) {
            super(context);
            getHolder().addCallback(this);
            setFocusable(true);
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            bgsrc = new Bitmap[5];
            for (int i=0;i<bgsrc.length;i++){
                bgsrc[i] = Bitmap.createBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.mountain_background_v2), i*800,0,800,399);
            }
            for (int i=bgsrc.length-1;i>=0;i--){
                if (i==0 || i==2) continue;
                backgrounds.add(new Background(bgsrc[i],-10+i*2 ));
            }

            //create GameThread Object and start Thread
            gameThread = new GameThread(getHolder(),this);
            gameThread.setRunning(true);
            gameThread.start();
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            boolean retry = true;
            int counter =0;
            while(retry && counter<1000){
                counter++;
                try{
                    gameThread.setRunning(false);
                    gameThread.join();retry = false;
                    gameThread = null;
                }catch (InterruptedException e){
                    e.printStackTrace();
                }

            }
        }

        public void update(){

               for (Background background: backgrounds){
                   background.update();
               }
        }

        @Override
        public void draw(Canvas canvas){
            super.draw(canvas);
            final float scaleFactorX = getWidth()/(WIDTH*1.f);
            final float scaleFactorY = getHeight()/(HEIGHT*1.f);
            if (canvas!=null){
                final int saveCount = canvas.save();
                canvas.scale(scaleFactorX,scaleFactorY);

                for (Background background: backgrounds){
                    background.draw(canvas);
                }
                canvas.restoreToCount(saveCount);
            }
        }
    }

当我在Canvas From Arraylist上绘制位图时,我的绘图非常慢,在GameThread Class I初始化FPS(每秒帧数)= 60,但是在Scaling Canvas后它变得很慢,我已经尝试在绘制之前缩放位图,但仍然相同性能。没有阵列我的意思是单个图像绘图好,我怎么能解决这个问题,并获得我想要的确切速度.. plz帮助我...谢谢..

1 个答案:

答案 0 :(得分:0)

draw()中的额外调用和计算会导致帧速率显着降低。在初始化阶段,我宁愿做一次所需的位图缩放,并保持较高的帧速率。