How to redraw SurfaceView using invalidate() metod?

南楼画角 提交于 2019-12-11 06:45:49

问题


I have a class GameBoard which extends SurfaceView. Inside I have an OnDraw method:

@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int size  = getWidth()/8;
        canvasSize = size;
        pawnBitmap[0] = bigPawn;
        pawnBitmap[1] = smallPawn;
        float left_distance;
        float top_distance;
        for(int j = 0; j < 10; j++){
            for (int i =0; i < 4; i++){
                left_distance = i*size+(float)50;
                top_distance = j*size+(float)10;
                canvas.drawBitmap(pawnBitmap[0], left_distance, top_distance, paint);
                canvas.drawBitmap(pawnBitmap[1], 6*size+i*30+(float)10, top_distance+30, paint);
            }
        }

    }

pawnBoard, bigPawn and smallPawn are public in this class and they are like:

public BitmapFactory myBitmapFactory = new BitmapFactory();

public  Bitmap[] pawnBitmap = new Bitmap[2];
public Bitmap bigPawn =  Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.game_button_2), 90, 90, false);
public Bitmap smallPawn = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.game_button_2), 30, 30, false);

I have also a second method in which I'm changing the image of bigPawn and smallPawn :

public void setBitmaps(Bitmap one, Bitmap two){
        this.paint = new Paint();
        this.bigPawn = one;
        this.smallPawn = two;
        this.tmp=4;
        invalidate();

    }

But after calling this method inside another (inside another class), the images are not changing. I checked using the tmp variable if setBitmaps() method really changes the images, and this is correct. But the invalidate function doesn't work. Why? Here is how I'm calling the setBitmaps method:

public void savePermutation(View view){

        Bitmap tmpBitmap1 = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.blue), 230, 230, false);
        Bitmap tmpBitmap2 = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.blue), 100, 100, false);
        myGameBoard.setBitmaps(tmpBitmap1, tmpBitmap2);


    }

I was looking for the solution, but none of this which I found was helpfull.


回答1:


Override surfaceCreated(). Then add this line:

setWillNotDraw(false);


来源:https://stackoverflow.com/questions/14676741/how-to-redraw-surfaceview-using-invalidate-metod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!