我正在创建一个应用程序,它会拍摄图像并将其置于屏幕上以进行更改。我正在使用SurfaceView和Canvas。我试图将SurfaceView置于父RelativeLayout中心。我让它工作,但它会在旋转时扭曲。所以我正在使用surfaceChanged方法在方向改变时重置位图和画布的大小:
@Override
public void surfaceChanged (SurfaceHolder holder, int format, int width, int height) {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
bitmap_width = height * imageRatio;
bitmap_height = height;
} else {
bitmap_width = width;
bitmap_height = width / imageRatio;
}
canvas_width = (int) bitmap_width;
canvas_height = (int) bitmap_height;
try {
canvas_bitmap = Bitmap.createScaledBitmap(initial_bitmap, (int) bitmap_width, (int) bitmap_height, true);
surface_canvas = new Canvas();
surface_canvas.setBitmap(canvas_bitmap);
} catch (Exception exception) {
exception.printStackTrace();
}
}
现在可以使用缩放功能,但现在它不会居中。我还注意到背景的其余部分是黑色的,而不是过去的灰色。这会让我相信画布超出了位图的视野。经过进一步检查,我注意到surfaceChanged方法在启动时被调用两次。所以我开始记录所有内容,这就是我发现的内容:
07-27 16:39:21.363 2129-2129/com... E/SURFACE_CHANGED﹕ imageRatio: 1.3333334 width: 1080 height: 1701 bitmap_width: 1080.0 bitmap_height: 810.0 canvas_width: 1080 canvas_height: 810 surface_width: -1 surface_height: -2
07-27 16:39:21.388 2129-2129/com... E/SURFACE_CHANGED﹕ imageRatio: 0.0 width: 1080 height: 1701 bitmap_width: 1080.0 bitmap_height: Infinity canvas_width: 1080 canvas_height: 2147483647 surface_width: -1 surface_height: -2
最重要的是,imageRatio只在我的代码中设置一次,变为0.0。因此,将位图的高度或宽度设置为无穷大。如果我旋转设备,会出现一组类似的两个日志,原始imageRatio设置为1.33 ...然后更改为0.0。我不能为我的生活弄清楚为什么会这样。
无论如何,这很容易避免。我把我的代码包装成if语句指定(imageRatio> 0.0)。然而问题仍然存在,没有任何变化!
答案 0 :(得分:0)
好的,我明白了。实际SurfaceView的宽度和高度没有改变以匹配位图的大小,因此我必须在调用surfaceChanged之前更改SurfaceView的大小。所以我重写onConfigurationChanged以使用surfaceHolder.setFixedSize()更改SurfaceView本身的大小,最终调用surfaceChanged:
@Override
public void onConfigurationChanged(Configuration config) {
super.onConfigurationChanged(config);
int screenWidth = screenSize.x;
int screenHeight = screenSize.y;
float width;
float height;
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
screenHeight = screenSize.x;
width = screenHeight * imageRatio;
height = screenHeight;
} else if (config.orientation == Configuration.ORIENTATION_PORTRAIT) {
screenWidth = screenSize.x;
width = screenWidth;
height = screenWidth / imageRatio;
} else {
Log.e("UNSUPPORTED_ORIENTATION", Integer.toString(config.orientation));
width = screenWidth;
height = screenHeight;
}
surfaceHolder.setFixedSize((int) width, (int) height);
}
然后我使用surfaceChanged设置画布和位图的宽度和高度以匹配surfaceView:
@Override
public void surfaceChanged (SurfaceHolder holder, int format, int width, int height) {
bitmapWidth = width;
bitmapHeight = height;
canvasWidth = width;
canvasHeight = height;
try {
canvasBitmap = Bitmap.createScaledBitmap(initialBitmap, (int) bitmapWidth, (int) bitmapHeight, true);
surfaceCanvas = new Canvas();
surfaceCanvas.setBitmap(canvasBitmap);
} catch (Exception exception) {
exception.printStackTrace();
}
}