0

I am tring to draw a square in the center of the screen. I want there to be a slight margin to the left and right of the square so that is is away from the edge, the way I am trying to create it is below. The problem is that it will not display properly on all devices and that when the screen is tilted some of the square is cut off. I think this is because I use rectSide = 1000. does anybody know a better way to do this that will work on any screen size?

int rectside =1000;
canvas.drawRect(width/2 - rectSide/2,
                height/2 - rectSide/2,
                width/2 + rectSide/2,
                height/2 + rectSide/2, paint);
Ciaran
  • 697
  • 1
  • 12
  • 35

3 Answers3

1

You need to get height and width of device programmatically like this

 DisplayMetrics displaymetrics = new DisplayMetrics();
 getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
 int height = displaymetrics.heightPixels;
 int width = displaymetrics.widthPixels;

Update:As pointed out by @Der Golem take the smaller between width and height so that all sides should be equal

Shakeeb Ayaz
  • 6,200
  • 6
  • 45
  • 64
1

Get the device's dimension:

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;

Next, get the smallest dimension:

int diameter = width;
if (height < width){
    diameter = height;
}

Now get an offset, I suggest using some kind of percentage of the device, e.g.

int offset = (int) (0.05*diameter);
diameter -= offset;

Finally draw it:

canvas.drawRect(width/2 - diameter/2 ,
                height/2 - diameter/2,
                width/2 + diameter/2,
                height/2 + diameter/2, paint);
Roel Strolenberg
  • 2,922
  • 1
  • 15
  • 29
  • Before I forget, if the landscape changes mess up your rectangle, make sure to put all of this in a method which you can redraw whenever a UI update is required (and don't forget to clear the canvas :) ). – Roel Strolenberg Jun 22 '15 at 09:30
0

You are right, using an absolute number of pixel is not the good way.

You should adapt your rectSide using display height & width. How to get screen size attributes has already been discussed here.

I also strongly recommend you to read this, to get a better understanding of how to manage multiple screen sizes.

Community
  • 1
  • 1
mlumeau
  • 821
  • 1
  • 8
  • 20