[英]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.