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