How to get the width and height of an android.widget.ImageView?

后端 未结 10 1928
长情又很酷
长情又很酷 2020-11-22 16:53
╔══════════════════════════════════════════════╗   ^
║ ImageView    ╔══════════════╗                ║   |
║              ║              ║                ║   |
║              


        
10条回答
  •  情书的邮戳
    2020-11-22 17:38

    If you have created multiple images dynamically than try this one:

    // initialize your images array

    private ImageView myImages[] = new ImageView[your_array_length];
    

    // create programatically and add to parent view

     for (int i = 0; i < your_array_length; i++) {
                    myImages[i] = new ImageView(this);
                    myImages[i].setId(i + 1);
                    myImages[i].setBackgroundResource(your_array[i]);
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                            frontWidth[i], frontHeight[i]);
                    ((MarginLayoutParams) params).setMargins(frontX_axis[i],
                            frontY_axis[i], 0, 0);
                    myImages[i].setAdjustViewBounds(true);
                    myImages[i].setLayoutParams(params);
    
                    if (getIntent() != null && i != your_array,length) {
                        final int j = i;
                        myImages[j].getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                            public boolean onPreDraw() {
                                myImages[j].getViewTreeObserver().removeOnPreDrawListener(this);
                        finalHeight = myImages[j].getMeasuredHeight();
                            finalWidth = myImages[j].getMeasuredWidth();
                        your_textview.setText("Height: " + finalHeight + " Width: " + finalWidth);
                                return true;
                            }
                        });
                    }
                    your_parent_layout.addView(myImages[i], params);
                }
    

    // That's it. Happy Coding.

提交回复
热议问题