我的任务是使图像适合 ImageView 并保持纵横比。所以我需要裁剪图像以保持 ImageView 纵横比。
我有来自相机的图像,尺寸为 320x240。我的屏幕尺寸是 480x320(横向模式) 应用程序只能横向模式,但不能全屏。
ImageView 填充父级。布局 XML 是:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/image"
android:layout_height="fill_parent"
android:layout_width="fill_parent" android:keepScreenOn="true" android:scaleType="fitCenter">
</ImageView>
</LinearLayout>
使用 image.getWidth() 和 image.getHeight() 我得到 480x270 大小。
我的代码:
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
MySize msize = main.imageSize();
//msize.height += 30; <----this fix my problem, but I dont undersand why?
Size size = camera.getParameters().getPreviewSize();
double kw = (double)size.width / (double)msize.width;
double kh = (double)size.height / (double)msize.height;
double k = Math.min(kw, kh);
Log.d("INFO", "msize before" + msize);
msize.width = (int)Math.ceil(msize.width * k);
msize.height = (int)Math.ceil(msize.height * k);
int left = (size.width - msize.width) / 2;
int top = (size.height - msize.height) / 2;
Log.d("INFO", "msize " + msize);
Log.d("INFO", "size " + size.width + "x" + size.height);
YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21, size.width, size.height, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvimage.compressToJpeg(new Rect(left, top, msize.width, msize.height), 80, baos);
byte[] jdata = baos.toByteArray();
Bitmap image = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
main.updateImage(image);
}
其中 msize 是 ImageView 大小,size 是 Camera 图片大小。在此之后,相机图像将被裁剪为:320x180,结果为:
https://www.dropbox.com/s/9e2xwdc6m88ty34/SC20120705-121813.png
如果我将 30 添加到 ImageView 高度,我得到了正确的结果。
我的安卓是 2.3.3。