在SurfaceView中设置图像背景,出现黑屏



好的,所以我尝试将一个SurfaceView的背景设置为JPG文件。但是它似乎不想绘制图像,我得到的只是一个黑屏。

下面是我的代码:
    public class FloorplanActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MapView mapView = new MapView(getApplicationContext());
    setContentView(mapView);

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.floorplan, menu);
    return true;
}
class MapView extends SurfaceView{
    Rect testRectangle1 = new Rect(0, 0, 50, 50);
    Bitmap scaled;
    int x;
    int y;
    public MapView(Context context) {
        super(context);
    }
    public void surfaceCreated(SurfaceHolder arg0){
        Bitmap background = BitmapFactory.decodeResource(getResources(), R.drawable.floorplan);
        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);
    }
 public void onDraw(Canvas canvas) {
        canvas.drawBitmap(scaled, 0, 0, null); // draw the background
    }

不知道为什么它不会绘制我保存在draw_mdpi文件夹中的"floorplan"图像。

谁有什么建议?

谢谢。

编辑:在做了一些调试断点后,似乎"缩放"变量由于某种原因变得"无穷大",因此newWidth和newHeight变量变得小于0,应用程序崩溃。

这只是当我把整个surfaceCreated移动到构造函数中,如果我把代码留在这里,那么它除了显示黑屏之外什么也不做。

首先,你应该实现SurfaceHolder。与MapView类的回调接口,并将其设置为它的SurfaceHolder的回调,使应用程序调用你的onSurfaceCreated()方法。其次,如果你想调用onDraw()方法,那么在MapView的构造函数中调用setWillNotDraw(false)。

我已经这样做了:

public class MapView extends SurfaceView implements SurfaceHolder.Callback {
    private Bitmap scaled;
    public MapView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);
        getHolder().addCallback(this);
    }
    public void onDraw(Canvas canvas) {
        canvas.drawBitmap(scaled, 0, 0, null); // draw the background
    }
    @Override
    public void surfaceCreated(SurfaceHolder arg0) {
        Bitmap background = BitmapFactory.decodeResource(getResources(), R.drawable.dr);
        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);
    }
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        // TODO Callback method contents
    }
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Callback method contents
    }
}

效果很好。注意:将MapView类移动到一个单独的*.java文件中。更新手表复制复制移动

最新更新