好的,我试图将 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 移动到构造函数中时,如果我将代码保持原样,那么除了显示黑屏之外它不会做任何事情。
不知道是什么原因导致它这样做......