Android系统。如何重新调整位图大小以适合SurfaceView中的屏幕

时间:2014-07-25 02:18:51

标签: android bitmap surfaceview

我想在SurfaceView中设置背景图像,但我无法将其缩放到屏幕大小。我该如何设置?

我当前的代码:

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);

      }

  }

}

我尝试应用this的最佳答案,但似乎无法弄清楚如何使用矩阵。

1 个答案:

答案 0 :(得分:2)

将位图缩放到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);

然后在你用来绘制的方法中:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    Paint paint = new Paint();
    canvas.drawBitmap(scaledBitmap, 0, 0, paint);
}

希望这有帮助