我试图在全屏幕ImageView中显示图像。除了零,我一直得到一个例外。如何获得ImageView的宽度和高度,以便我可以缩放图像?
如果我对尺寸进行硬编码,一切都按预期工作。
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
public class SingleImageActivity extends Activity{
private ImageView mFullPageImage;
private static final String SELECTED_FILEPATH = "msd.com.example.dailyselfie.selected_filepath";
private String filepath;
int targetW;
int targetH;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_image_activity);
mFullPageImage = (ImageView) findViewById(R.id.fullPageImageView);
filepath = getIntent().getExtras().getString(SELECTED_FILEPATH);
processPicture(filepath);
//Toast.makeText(this, filename, Toast.LENGTH_SHORT);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
targetW = mFullPageImage.getWidth();
targetH = mFullPageImage.getHeight();
}
protected void processPicture(String filepath){
//targetW = mFullPageImage.getWidth();
//targetH = mFullPageImage.getHeight();
//targetW = 400;
//targetH = 400;
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filepath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(filepath, bmOptions);
//display with no options
//Bitmap bitmap = BitmapFactory.decodeFile(filepath);
mFullPageImage.setImageBitmap(bitmap);
}
}
答案 0 :(得分:0)
如果您尝试全屏设置位图,可以使用下面的代码来获取屏幕的宽度和高度。
WindowManager wm = (WindowManager) mContext
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width=size.x;
int height= size.y;
答案 1 :(得分:0)
您收到divide by zero exception
,因为targetW
和targetH
的值为零。在这一行中,您试图将值除以零
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
如果您在Android完成在屏幕上绘制它之前在任何视图上调用getHeight
或getWidth
方法,它将返回零。
所以请使用ViewTreeObserver
我想要问的另一件事是你是在尝试保持图像的宽高比,或者如果图像被拉伸你就可以了。