Search code examples
androidkotlinandroid-imageviewandroid-view

Set position of a View from the centre instead of top left


I have a image view initialized in code. I am able to set the position via setX() and setY(). methods. As I understand, these coordinates are set to the top left corner of the image. However, I want to set the position according to the center of the image. Is this possible?

Note: I am new in Android development


Solution

  • No, you cannot set the position according to the center.

    But, you can calculate the position the top left corner should be, for the center to be in a specific x,y location, by subtracting half the width and height respectively.

    You can call getWidth() and getHeight() to get them.

    So, you can do something like this:

    fun setViewPositionAccordingToCenter(view: View, x: Int, y: Int){
    
        view.setX(x - (view.getWidth()/2))
        view.setY(y - (view.getHeight()/2))
    }