繁体   English   中英

我怎样才能获得我在Android中的视图中心x,y?

[英]How can i get center x,y of my view in android?

我在我的框架布局上添加了一个imageview。 在这里,我想得到我的imageview中心坐标。 我将使用相同的坐标在下一个布局中设置我的imageview。 请建议我如何获得我的imageview的中心坐标。

提前致谢

imageView的中心将是

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

但请确保在imageView创建后调用它

您可以使用getPivotX()getPivotY() ,它始终保持在视图中心甚至旋转视图。

试试这个 :

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));

希望这对你有所帮助。

谢谢。

正如@aiueoH所提到的,你可以使用getPivotX() and getPivotY()

尝试使用它来查找中心坐标:

int centreX = view.getPivotX()/2;
int centreY = view.getPivotY()/2;

如果你想在其他视图的中心对齐一个视图,那么你可以使用这个 -

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

然后显然使用 -

child_view.setX(center_x);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM