7

我正在尝试计算此图像的尺寸,它将使用这条线从网上下载imgLoader.DisplayImage(url, R.drawable.thumbnail_background, image);。问题是 orgHeight 变为零,您不能除以零。但是为什么是orgHeight0?

// Add the imageview and calculate its dimensions
        //assuming your layout is in a LinearLayout as its root
        LinearLayout layout = (LinearLayout)findViewById(R.id.layout);

        ImageView image = (ImageView)findViewById(R.id.photo);

        ImageLoader imgLoader = new ImageLoader(getApplicationContext());
        imgLoader.DisplayImage(url, R.drawable.thumbnail_background, image);

        int newHeight = getWindowManager().getDefaultDisplay().getHeight() / 2;
        int orgWidth = image.getWidth();
        int orgHeight = image.getHeight();

        //double check my math, this should be right, though
        int newWidth = (int) Math.floor((orgWidth * newHeight) / orgHeight);

        //Use RelativeLayout.LayoutParams if your parent is a RelativeLayout
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            newWidth, newHeight);
        image.setLayoutParams(params);
        image.setScaleType(ImageView.ScaleType.CENTER_CROP);
        layout.updateViewLayout(image, params);     

我的 imageView xml 是这样的:

<ImageView
            android:id="@+id/photo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
        />  
4

2 回答 2

12

视图尚未放置在onCreate()方法中,因此它们的尺寸为 0。发布RunnablefromonCreate()以获取正确的值:

image.post(new Runnable() {

 @Override
 public void run() {
    int newHeight = getWindowManager().getDefaultDisplay().getHeight() / 2;
    int orgWidth = image.getWidth();
    int orgHeight = image.getHeight();

    //double check my math, this should be right, though
    int newWidth = (int) Math.floor((orgWidth * newHeight) / orgHeight);

    //Use RelativeLayout.LayoutParams if your parent is a RelativeLayout
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
        newWidth, newHeight);
    image.setLayoutParams(params);
    image.setScaleType(ImageView.ScaleType.CENTER_CROP);
    layout.updateViewLayout(image, params);      
 } 

});
于 2013-04-27T13:15:32.430 回答
2

您还可以在布局完成后立即使用 ViewTreeObserver 获取值。

Ref -你怎么知道布局何时被绘制?

于 2013-04-27T13:18:46.567 回答