Kamalone
Kamalone

Reputation: 4115

how can i draw canvas bitmap's in properly in every screen resolution in android

I am using canvas to display some textures on the screen and I can able to display them on the screen.The only problem i am facing is, it works well in emulator but when it comes to device the textures are being scattered this is due to difference in screen resolution.can you tell me how to how can i solve this problem

and here is my code for placing textures on screen

                   Bitmap bitmap = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.dial);
                   canvas.drawBitmap(bitmap, canvas.getWidth()/10, canvas.getHeight()/4, null);


                   Bitmap bitmap1 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.browser);
                   //canvas.drawBitmap(bitmap1, bitmap.getWidth()/4 ,canvas.getHeight()/2, null);
                   canvas.drawBitmap(bitmap1, canvas.getWidth()/5 ,canvas.getHeight()/2, null);


                   Bitmap bitmap2 = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.camera);
                   canvas.drawBitmap(bitmap2, canvas.getWidth()/10 + bitmap.getWidth()/6,canvas.getHeight()/3, null);

Upvotes: 1

Views: 1264

Answers (1)

LeffelMania
LeffelMania

Reputation: 12875

You basically need to transform your canvas so that you're always working with a predictable coordinate system. If you're not familiar with coordinate systems you'll likely want to read up on that, but the basic idea is:

  • Determine how how big you want your canvas to be
  • Determine how big your screen is
  • Scale your canvas such that its coordinates match that of the screen
  • Draw your bitmaps with sizes and coordinates based on your own defined coordinate system.

Example:

You want to draw on a canvas that's 640x480. Your screen has a resolution of 800x400. Scale your canvas by (800/640) in the x direction and (480/400) in the y direction. Now coordinate 0,0 is in the top left and 640,480 is in the bottom right. Draw as needed.

You can obviously tweak this to account for aspect ratio and whatnot, but the idea is that you want to define the size and location of your bitmaps in terms of your own coordinate system, not just the resolution that the device gives you.

Upvotes: 2

Related Questions