簡體   English   中英

如何獲得圖像視圖的寬度和高度

[英]How to get the width and heigh of an imageview

我有以下XML代碼:

<LinearLayout
 android:id="@+id/linearLayoutInner"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@layout/gallery_image_background"
/>

然后這段代碼:

LinearLayout linearLayoutInner = (LinearLayout) findViewById(R.id.linearLayoutInner);
ImageView imageView = new ImageView(thisActivityContext);
imageView.setImageResource(R.drawable.example);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
imageView.setLayoutParams(lp);
linearLayoutInner.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
linearLayoutInner.addView(imageView);

然后,我調用一個自己的函數,該函數用於縮放位圖圖像,直到側面之一達到邊緣為止(即,因此,如果原始位塊的寬度是其兩倍高,它將保持比例在imageview內,這顯然不是任何scaletype設置支持):

SharedCode.sharedUtilScaleImage(imageView);

問題來了。 該函數需要知道包含可繪制位圖的視圖的大小。 如果ImageView的行為正確,它應該使用MATCH_PARENT並因此得到linearLayoutInner的寬度/高度。 但是,以下代碼返回零:

int heightParent = max(imageView.getLayoutParams().height, imageView.getHeight());      
int widthParent = max(imageView.getLayoutParams().width, imageView.getWidth());

我該如何解決? 為什么我返回0而不是正確的高度/寬度?

您可能在調用View的onMeasure()之前就太早調用了代碼。 在此之前,它的大小是未知的。

final ImageView iv....
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        //Measure
        iv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    }
});
final ImageView imageView = (ImageView )findViewById(R.id.image_test);
    ViewTreeObserver vto = imageView.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            imageView .getViewTreeObserver().removeGlobalOnLayoutListener(this);
            imageView.getHeight(); // This will return actual height.
            imageView.getWidth(); // This will return actual width.
        }
    });    

似乎您可能正在從onCreate()調用。 ü需要等待活動的窗口,連接,然后調用getWidth()getHeight()imageView 。您可以嘗試調用getWidth()getHeight()onWindowFocusChanged()的活動的方法。

編輯

@Override
public void onWindowFocusChanged(boolean hasFocus){
    int width=imageView.getWidth();
    int height=imageView.getHeight();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM