41

I am attaching an imageview up on my frame layout. Here i want to get my imageview center co-ordinates. i will use that same co-ordinates to set my imageview in next layout. Please suggest me how to get the center co-ordinates of my imageview.

Thanks in advance

Raghu Mudem
  • 6,793
  • 13
  • 48
  • 69

5 Answers5

84

centre of the imageView will be

 centreX=imageView.getX() + imageView.getWidth()  / 2;
 centreY=imageView.getY() + imageView.getHeight() / 2;

but make sure you call it after the imageView created

BRPocock
  • 13,638
  • 3
  • 31
  • 50
Mohsin Naeem
  • 12,542
  • 3
  • 39
  • 53
9

You can use getPivotX() and getPivotY(), it always keep in center of view even rotate view.

aiueoH
  • 728
  • 1
  • 8
  • 24
5

Try this :

ImageView my_image = (ImageView) findViewById(R.id.my_imageView);  

Rect rectf = new Rect();
my_image.getLocalVisibleRect(rectf);

Log.d("WIDTH        :",String.valueOf(rectf.width()));
Log.d("HEIGHT       :",String.valueOf(rectf.height()));
Log.d("left         :",String.valueOf(rectf.left));
Log.d("right        :",String.valueOf(rectf.right));
Log.d("top          :",String.valueOf(rectf.top));
Log.d("bottom       :",String.valueOf(rectf.bottom));

Hope this helps you.

Thanks.

Dipak Keshariya
  • 22,193
  • 18
  • 76
  • 128
Pratik Sharma
  • 13,307
  • 5
  • 27
  • 37
4

As @aiueoH mentioned, you can use getPivotX() and getPivotY().

Try using this for finding coordinates of centre:

int centreX = view.getPivotX()/2;
int centreY = view.getPivotY()/2;
NickitaX
  • 352
  • 2
  • 14
  • 1
    Perhaps divide by 2 is unneeded? The [documentation states](https://developer.android.com/reference/android/view/View.html#isPivotSet()) "If no pivot has been set then the pivot will be the center of the view." – user650881 Jul 13 '18 at 10:00
2

if you wish to align a view at the center of other view then you can use this -

float center_x = parent_view.getX() + parent_view.getWidth()/2 - child_view.getWidth()/2;

and then obviously using -

child_view.setX(center_x);
Akshay Sahai
  • 2,121
  • 1
  • 17
  • 20