Positioning an image at a specific X and Y location not consistent between tablets

106 Views Asked by At

I would like to position an image of a mouse over a wallpaper containing different mouse holes. My the scale type for my wallpaper mouseHole is set to CENTER_CROP

I am setting the X and Y positions of my mouse using the following code:

int mouseX = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, xLoc, getResources().getDisplayMetrics());
int mouseY = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, yLoc, getResources().getDisplayMetrics());

However, on two different tablets (specifically a Samsung Galaxy Tab 5 vs. an Asus ZenPad 10), the locations do not perfectly match. The wallpaper is an image with four different mouse holes, and I would like the location of the mouse to match on all tablets.

2

There are 2 best solutions below

2
On

Take a look at developer guide for supporting multiple screen sizes here

TLDR: you can set in your android manifest to allow only users with the screen sizes specified in this section to be able to see and download your application. OR create different layouts for different screen sizes, it is more work but it is what you need :)

0
On

You can not use fixed locations with an ImageView and scaleTypes.

As soon as the image is scaled, you have to apply the same transformation to your mouse coordinates.

An example with scale types

This is basically what you have been doing and why there is an error, a bit exaggerated though.

Given an image 100x100px

  • Mouse A at [100px, 100px] of the image
  • Mouse B at [5,5]

(I'm not taking densities into account yet)

Given an imageView with `height 100px, width 50px.

Using centerCrop, this will scale the image: half the width, and offset the height, resulting in the following

  • mouse A would still be at [100, 100], which would be outside of the view (width is 50), while
  • mouse B would be drawn at [5,5] from the top, which would resolve to [10, 30] on the image before scaling and cropping

You'd have to apply the same scaling to your points as you did to your image: [x/2, y - 25] in this sample.

Scale yourself!

You will need to scale the bitmap yourself. Do some computation, get the offset and apply it to your bitmap and positions.

Densities

Densities are not really a problem here, since you can just calculate the positions for all densities and set those values in the value-mdpi etc folders.