Reputation: 5
I would like to set up a background image in my SurfaceView, but I can't get it to scale to the size of the screen. How can I set that up?
My Current Code:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MySurface extends SurfaceView implements Runnable {
SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = true;
Bitmap Background;
Bitmap clouda;
public MySurface(Context context) {
super(context);
init(context);
}
public MySurface(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MySurface(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
// do stuff that was in your original constructor...
ourHolder = getHolder();
ourThread = new Thread(this);
ourThread.start();
Background = BitmapFactory.decodeResource(getResources(), R.drawable.island);
clouda = BitmapFactory.decodeResource(getResources(), R.drawable.clouda);
}
public void pause(){
}
public void resume(){
}
@Override
public void run() {
// TODO Auto-generated method stub
while(isRunning){
if (!ourHolder.getSurface().isValid())
continue;
Canvas canvas = ourHolder.lockCanvas();
canvas.drawBitmap(Background, 0, 0, null);
canvas.drawBitmap(clouda, 0, 0, null);
ourHolder.unlockCanvasAndPost(canvas);
}
}
}
I have tried to apply the top answer of this, but can't seem to figure out how to use the matrix.
Upvotes: 0
Views: 2744
Reputation: 77
To scale the bitmap to the size of the SurfaceView
//The following two are just for viewing sake, they should be defined somewhere
SurfaceView targetSurfaceView;
Bitmap mySourceBitmap;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(mySourceBitmap,
targetSurfaceView.getWidth(),
targetSurfaceView.getHeight(),
true);
Then in the method you use to draw:
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
canvas.drawBitmap(scaledBitmap, 0, 0, paint);
}
Hope this helps
Upvotes: 2