Ciaran
Ciaran

Reputation: 695

how to draw a square in the centre of the screen in android

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);

Upvotes: 0

Views: 1894

Answers (3)

Roel Strolenberg
Roel Strolenberg

Reputation: 2950

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);

Upvotes: 1

mlumeau
mlumeau

Reputation: 811

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.

Upvotes: 0

Shakeeb Ayaz
Shakeeb Ayaz

Reputation: 6096

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

Upvotes: 1

Related Questions