Search code examples
androidimageandroid-layoutandroid-screen

Is There any way to Predict x and y location from one screen size to another?


i am developing an android app, about joining dots and making picture. so far i can't find a way to extract exact x and y coordinates of black dots . so I've hard coded x and y locations to draw point on exact black dot of image. It worked wonderful on 1152*720 size ,but problem occurs when i tested it on 480*600 size , dots misplaced from there exact location , now

My Question is if I've written something like :

x = 100 , y = 200 (on screen 1152*720)

what will be x and y values in different screen sizes like 480*600 and how to calculate it ? i know it is silly question but i am new to this stuff.


Solution

  • Answering your question as you have asked it...

    int oldScreenX // The current x coord
    int newScreenX // The new x coord
    ...
    float oldScreenSizeX = 1152.0f;
    float newScreenSizeX = 600.0f;
    newScreenX = (int)(oldScreenX / oldScreenSizeX) * newScreenSizeX; // Remember to cast the result back to an int
    

    Do the same for y.


    Additional:

    Perhaps you should reconsider your approach.
    The real problem is how do you put the dot in the same location on the Image, if the Image is being drawn at a different size. So forget about measuring the screen size. Measure the Image size instead.
    For example, if you are showing your image in an ImageView, you could write a general scaling method like the following:

    public int scaleCoordinate(int unscaledImageSize, int scaledImageSize, int unscaledCoordinate) {
        scaledCoordinate = (int)(unscaledCoordinate / unscaledImageSize) * scaledImageSize; // Remember to cast the result back to an int
        return scaledCoordinate;
    }
    

    Then you can use it in your code, something like:

    ImageView imageView = (ImageView)findViewById(R.id.my_imageview);
    Drawable drawable = image.getDrawable();
    
    // Get the original size of the bitmap
    int unscaledSizeX = drawable.getIntrinsicWidth();
    
    // Get the current size it is being drawn at on the screen
    int scaledSizeX = imageView.getWidth();
    
    int scaledCoordinateX = scaleCoordinate(unscaledSizeX, scaledSizeX, unscaledCoordinateX);
    

    NOTE:
    The ImageView needs to be measured and laid out by the system before calling the above code. If you call it too early imageView.getWidth() will return 0.
    It would be best to call the above code once the ImageView is actually displayed on the screen (from your onResume() or later).