Android : Surface view and scaling

on Thursday, January 29, 2015


Before all, I apologies for my English.


I'm a newbie in programming of Android App and I recently discovered the Canvas and Bitmap, so I decided to make a "Game" that can only use landscape. I discovered too the SurfaceView and how implement a background on my SurfaceView, but the first of all is that my background is an image 496x288.


I was searching in internet to learn how I can scaled well to fill all the screen of my phone with the background, and another screens. So I find this code and try to use in my app.



@SuppressLint("WrongCall")
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
Bitmap background = BitmapFactory.decodeResource(getResources(), R.drawable.fondo1escalado);
float scale = (float) background.getHeight() / (float) getHeight();
int newWidth = Math.round((background.getWidth() / scale));
int newHeight = Math.round(background.getHeight() / scale);
scaled = Bitmap.createScaledBitmap(background, newWidth, newHeight, true);
gameLoopThread.setRunning(true);
gameLoopThread.start();


}

@SuppressLint("WrongCall")
protected void onDraw(Canvas canvas) {

canvas.drawColor(Color.BLUE);
canvas.drawBitmap(scaled, 0,0, null);
}


It works, but it doesn't work well. I got this:


enter image description here (Don't worry about the character)


It scales well but don't fit all the screen (See the blue background).


So, like a good programmer I try to fix this using a GUI that I have designed wich dimensions are 296x912, I used the same code, and it scalates well in the Height but not in the Width for all the screens even a tablet.


enter image description here


This is the code of the GUI



float scalaInterfazAltura = (float) interfaz.getHeight() / (float) getHeight();
int newHeightInterfaz = Math.round(interfaz.getHeight() / scalaInterfazAltura);
int newWidthInterfaz = Math.round(interfaz.getWidth() / scalaInterfazAltura);
scaledinterfaz = Bitmap.createScaledBitmap(interfaz, newWidthInterfaz, newHeightInterfaz, true);
canvas.drawBitmap(scaledinterfaz, getWidth() - interfaz.getWidth()/2, 0, null);


So, my question is: There is a thing to scale well in Surfaceview? I'm doing something wrong?


Thank you.


0 comments:

Post a Comment