好的,我正在尝试将 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 移动到构造函数中时,如果我将代码保留在此处,那么它除了显示黑屏外不会做任何事情。
尽管不知道是什么导致它这样做......
最佳答案
首先,您应该使用 MapView 类实现 SurfaceHolder.Callback 接口(interface),并将其设置为其 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 文件。 更新观察复制复制移动
关于android - 在 SurfaceView 中设置图像背景,出现黑屏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15089784/