2

好的,我试图将 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
    }

不知道为什么它不会绘制我保存在 drawable-mdpi 文件夹中的“平面图”图像。

有人有什么建议吗?

谢谢。

编辑:使用断点进行一些调试后,似乎“缩放”变量由于某种原因变为“无穷大”,因此 newWidth 和 newHeight 变量变得小于 0 并且应用程序崩溃。

仅当我将整个 surfaceCreated 移动到构造函数中时,如果我将代码保持原样,那么除了显示黑屏之外它不会做任何事情。

不知道是什么原因导致它这样做......

4

1 回答 1

9

首先,您应该使用 MapView 类实现 SurfaceHolder.Callback 接口,并将其设置为其 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 文件中。更新观看重复复制移动

于 2013-02-26T15:31:17.650 回答