好吧,我試圖將SurfaceView的背景設置爲JPG文件。但它似乎並不想畫出圖像,而我得到的只是一個黑屏。在SurfaceView中設置圖像背景,變黑屏幕
這裏:我的代碼:
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
}
不知道爲什麼它不會畫我已經保存在繪製-MDPI文件夾中的「佈局規劃」的形象。
任何人有任何建議嗎?
謝謝。
編輯:在做了一些調試與斷點之後,似乎由於某些原因,「縮放」變量變成「無窮大」,因此newWidth和newHeight變量變得小於0並且應用程序崩潰。
這隻有當我將整個surfaceCreated移動到contstructor時,如果我在這裏保留代碼,那麼它不會執行任何beyind顯示黑屏的任何操作。
不知道是什麼原因引起的,雖然這樣做......
謝謝,解決了它! – Hallow 2013-03-03 16:35:34
雖然這是舊的,謝謝。我現在已經把這個問題砸得粉身碎骨。 – Alastair 2013-07-20 19:30:27
如果你想在背景上繪製一些東西,你可以去掉setWillNotDraw(false)的調用,否則你不管你畫什麼,都不會看到 – Braj 2013-08-29 09:39:31