0

I want to draw a rectangle using canvas which change its size with different screen size.
That means it increase of decrease its size with screen ratio.
I use the following code:

float scale = getContext().getResources().getDisplayMetrics().density;
canvas.drawRect(leftX-20*scale, leftY-20*scale, rightX+20*scale, rightY, mPaint); 

But it does not change its size in different screen.
What can I do?

oliholz
  • 7,447
  • 2
  • 43
  • 82
Farhana Haque
  • 1,371
  • 14
  • 23

2 Answers2

0

Or you can try

float scale= Resources.getSystem().getDisplayMetrics().densityDpi;

This is implemented in my Android Game "MaracasRunner".

zx485
  • 28,498
  • 28
  • 50
  • 59
0

The problem is in getContext().getResources().getDisplayMetrics().density; it wil give you same dencity always better use the following approach

To get density Use the following code

DisplayMetrics metrics = new DisplayMetrics();    
getWindowManager().getDefaultDisplay().getMetrics(metrics);    
int screenDensity = metrics.densityDpi;

so your code will be

DisplayMetrics metrics = new DisplayMetrics();    
    getWindowManager().getDefaultDisplay().getMetrics(metrics);    
    float scale = metrics.densityDpi;

canvas.drawRect(leftX-20*scale, leftY-20*scale, rightX+20*scale, rightY, mPaint); 
Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243