Devon Smith
Devon Smith

Reputation: 397

How to get Center of an Imageview which is a circle

Now I have an ImgeView which a circle and I want to find the center point of that circle so I have tried the following code but it seems not working

int[] location = new int[2];
            imageView.getLocationOnScreen(location);

int radius=imageView.getHeight()/2;
                    int[] center=new int[2];
                    center[0]=location[0]+radius;
                    center[1]=location[1]+radius;

so the coordinates I got by "location" is top point of the imageview or not ?

Please help me how to get a center point of an imageview.

Upvotes: 2

Views: 10984

Answers (3)

UndergroundFox
UndergroundFox

Reputation: 1301

Addition to Chandan's answer, say we are using the same code:

int centerXOnImage=myImageView.getWidth()/2;
int centerYOnImage=myImageView.getHeight()/2;

int centerXOfImageOnScreen=myImageView.getLeft()+centerXOnImage;
int centerYOfImageOnScreen=myImageView.getTop()+centerYOnImage;

if your myImageView.getWidth() is returning 0, you might want to do a little bit of modification:

myImageView.measure(0,0);
int centerXOnImage=myImageView.getMeasuredWidth()/2;
int centerYOnImage=myImageView.getMeasuredHeight()/2;

Notice, you might want to do this after myImageView is created in code and added to a root view.

Upvotes: 0

Chandan Adiga
Chandan Adiga

Reputation: 576

I assumed below situation:

You will be loading an ImageView(either from xml or code) and have a reference to the same in myImageView(say). Now, you wish to calculate the centre of the myImageView irrespective of its position on the screen.

If my assumption is correct then probably below is the solution you are looking for:

    int centerXOnImage=myImageView.getWidth()/2;
    int centerYOnImage=myImageView.getHeight()/2;

    int centerXOfImageOnScreen=myImageView.getLeft()+centerXOnImage;
    int centerYOfImageOnScreen=myImageView.getTop()+centerYOnImage;

Upvotes: 10

dorin
dorin

Reputation: 873

You can get the top-left corner coordinates using:

ImageView iv = (ImageView)findViewById(R.id.image_view);
Rect rect = iv.getDrawable().getRect();
int xOffset = rect.left;
int yOffset = rect.top;

Based on height/2 and width/2 you can establish the center of your ImageView .

Upvotes: 0

Related Questions