0

I know there are numerous other threads about this. I've been checking through them with no avail for the past 2 days and right now it's driving me nuts. So basically I have a spritesheet, which I load into a Bitmap, cut the frames apart, perform scaling on them and load them into a list for later animation. Scaling looks good ranging from ldpi to xhdpi, so does animation.

But there's another thing that bugs me, and that's the positioning on different devices. I draw them with canvas.drawBitmap(bitmap, srcRect, destRect, paint). Well, I guess code tells more than thousand words.

//converting dps to pixels
int xCoord = convertToPixels(100);
int yCoord = convertToPixels(150);

//defining destination rectangle; sprite is a Bitmap object
Rect destRect = new Rect(xCoord, yCoord, xCoord+sprite.getWidth(), yCoord+sprite.getHeight());

//drawing
canvas.drawBitmap(sprite, null, destRect, null);

convertToPixels(float dp) just returns a number of pixels with formula Math.round(dp*DENSITY).

I believe that if I specify dps, the aspect ratio on all devices should be the same, e.g. if I put something on 10% of the screen size of one device, it should maintain those 10% on another smaller/bigger/less dense/more dense screen. But I guess my logic is flawed, because it doesn't work. It draws sprites on different devices on different places.

To summarize: drawing a Bitmap object with destRect with x and y coords 100 dps should maintain ratio on all devices with respect to canvas size or I ought to think this way.

I would kindly ask you to help me with this matter, for I'm lost currently lost, more literally than figuratively. And please don't just give me a link to "Supporting Multiple Screens" topic on developer site or similar sites, because I've read them many times and yet it seems I don't understand them. Thank you!

1 Answers1

0

Are you sure the dip to px calculation is correct? I wrote the following code to do this:

public class ViewHelper {
    public static int getPxFromDip(int dips){
        return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dips, Application.getContext().getResources().getDisplayMetrics());
    }
}

Where Application.getContext() is the Application wide context, or provide the local Activity context.

Kevin Parker
  • 16,975
  • 20
  • 76
  • 105
  • I used formula found here on SO. Also I tried other formulas: the one with adding 0.5f (on official topic), the one calculating density from xdip and ydip and as well formula you provided above. None of them changes the result . I double-checked just to be sure. Thanks though. – x123y234z345 Jul 10 '12 at 05:40