7

この画像の寸法を計算しようとしています。この画像は、この行を使用して Web からダウンロードされます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です。 Runnablefromを投稿しonCreate()て、適切な値を取得します。

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 を使用して、レイアウトが完了するとすぐに値を取得することもできます。

参照 -レイアウトがいつ描画されたかをどのように知ることができますか?

于 2013-04-27T13:18:46.567 に答える