问题
Here is my snippet of code
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/framelayouts"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
>
<ImageView
android:id="@+id/imageviews"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:src="@drawable/ic_launcher" />
</FrameLayout>
now am able to get the image at center .
Problem:
Here Problem is i am getting some un used space top and bottom, how can i find the height of the unused space or height of the image or only the imageheight ?
Screenshot:
回答1:
private void getImageViewDimension() {
// TODO Auto-generated method stub
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
int actualImgWidth = mDeviceWidth - mImgView.getX();
int actualImgHeight = mDeviceHeight - mImgView.getY();
Toast.makeText(getApplicationContext(), "actualImgWidth ,actualImgHeight:" +actualImgWidth +","+actualImgHeight ,
Toast.LENGTH_SHORT).show();
int Width = mImgView.getWidth();
int Height = mImgView.getHeight();
}
}, 10L);
}
回答2:
You can find Image height using below code.
final ImageView layout = (ImageView) findViewById(R.id.imageviews);
ViewTreeObserver vto = layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int height = layout.getMeasuredHeight();
if (height > 0) {
Log.i("TAG", "height : " + height);
}
}
});
回答3:
You can calculate the height and width of the Imageview using ViewTreeObserver. Try this sample app.
public class MainActivity extends Activity {
int finalHeight, finalWidth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView iv = (ImageView)findViewById(R.id.imageviews);
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
iv.getViewTreeObserver().removeOnPreDrawListener(this);
finalHeight = iv.getMeasuredHeight();
finalWidth = iv.getMeasuredWidth();
Log.i("DIMEN", "Height: " + finalHeight + " Width: " + finalWidth);
return true;
}
});
}
}
But since you are using fillparent for your ImageView, you will get the entire width as the result.
来源:https://stackoverflow.com/questions/26992000/how-to-find-the-height-and-width-of-the-image-view-when-it-is-aligned-center-in