Cannot scale background image (android studio)

时间:2015-07-28 16:53:19

标签: java android image background

public class GameView extends SurfaceView {
private Bitmap bmp;
private SurfaceHolder holder;
private GameLoopThread gameLoopThread;
private int x = 0;
private int y = 0;
private int xSpeed = 1;
public static int WIDTH = 800;
public static int HEIGHT = 450;
private Background bg;

public GameView(Context context) {
    super(context);
    gameLoopThread = new GameLoopThread(this);
    holder = getHolder();
    holder.addCallback(new SurfaceHolder.Callback() {

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            boolean retry = true;
            gameLoopThread.setRunning(false);
            while (retry) {
                try {
                    gameLoopThread.join();
                    retry = false;
                } catch (InterruptedException e) {
                }
            }
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            bg = new Background(BitmapFactory.decodeResource(getResources(), R.drawable.tuo));
            bg.setVector(-5);
            gameLoopThread.setRunning(true);
            gameLoopThread.start();
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format,
                                   int width, int height) {
        }
    });
    bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic);
    // tutaj dorysować tło
}

@Override
protected void onDraw(Canvas canvas) {
    if (x == getWidth() - bmp.getWidth()) {
        xSpeed = -4;
    }
    if (x == 0) {
        xSpeed = 4;
    }
    x = x + xSpeed;
    final float scaleFactorX = getWidth()/WIDTH;
    final float scaleFactorY = getHeight()/HEIGHT;
    if(canvas!=null) {
        final int savedState = canvas.save();
        canvas.scale(scaleFactorX, scaleFactorY);
        bg.draw(canvas);
        canvas.restoreToCount(savedState);
    }
    canvas.drawBitmap(bmp, x , 10, null);

}


public void update()
{
    bg.update();
}


@Override
public boolean onTouchEvent(MotionEvent event) {
       x=x+10;
    return super.onTouchEvent(event);
}
}

I can't scale the image - it should make a scale by dividing getWidth/WIDTH (and height too) - WIDTH and HEIGHT are the image dimensions.

It just prints a left, upper corner of an image, like there is totally no scaling ;(

If someone have any idea, I would be thankful :)

1 个答案:

答案 0 :(得分:0)

你需要计算:

/*
    WIDTH/getWidth() = 4; // if ur image width = 200px
    scaleFactorX = 4*getwidth();
    scaleFactorY = 4*getHeight();
*/
final float scaleFactorX = WIDTH/getWidth();
final float scaleFactorY = HEIGHT/getHeight();
canvas.scale(scaleFactorX*getWidth(), scaleFactorY*getHeight());

我希望它们是比例的...

1600 * 900或类似的东西...... 400 * 225