0

I am Drawing a Rectangle on a Canvas by Doing the Following:

canvas.drawRect(0, 0, Screen.getCenterX(), Screen.getCenterY(), paint);

Screen is Set Up the following way:

public static int width;
public static int height;

public static void setupScale(Context context) {
    WindowManager wm = (WindowManager) context
            .getSystemService(Context.WINDOW_SERVICE);
    DisplayMetrics displaymetrics = new DisplayMetrics();
    wm.getDefaultDisplay().getMetrics(displaymetrics);
    height = displaymetrics.heightPixels;
    width = displaymetrics.widthPixels;
    Log.e("TEST", "TEST");
}

public static int getCenterX() {
    return width / 2;
}

public static int getCenterY() {
    return height / 2;
}

It also seems that the Log: "TEST" does not get called sometimes. The Screen.setup() function is called in my MainActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.game_layout);

    // SETUP ONCE:
    context = this;
    Screen.setupScale(context);

The Screen should display a rectangle that fills a quarter of the Screen. However, this is the Result: enter image description here

As you can see, the Rectangle appears in the top left corner. The worst part s that sometimes the Rectangle shows the way it should so it feels random. When I log Screen.width, it returns 16 for Some reason.

Here is my Relevant Manifest Info:

minSdkVersion 13
targetSdkVersion 21

What could be the issue here? Please Help. It seems that sometime that Log is showing and the Resolution is set. But other times it does not work. What is the issue here. It feels very random. Thank you very much.

Community
  • 1
  • 1

1 Answers1

0

Working from the answer here, why don't you try to call the getWindowManager() inside the setupScale() function instead of passing it along as a parameter.

public static void setupScale() {
    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    height = displaymetrics.heightPixels;
    width = displaymetrics.widthPixels;
    Log.e("TEST", "TEST");
}
Community
  • 1
  • 1
Niddro
  • 1,705
  • 2
  • 12
  • 24
  • I have to pass context along as a parameter, because the setupScale is not an Activity. –  Mar 04 '15 at 08:05
  • 1
    Then try looking at the answer above the one I linked to. There's an explanation on how to get the screen width and height if you're not in an activity that differs slighty from what you've already tried. Perhaps you'll find something there. Good luck! – Niddro Mar 04 '15 at 08:18