I need to find out the screen resolution and divide it in half to draw a square.

Implemented as follows:

public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new DrawView(this)); } class DrawView extends SurfaceView implements SurfaceHolder.Callback { private DrawThread drawThread; Paint p; Rect rect; public DrawView(Context context) { super(context); getHolder().addCallback(this); p = new Paint(); rect = new Rect(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceCreated(SurfaceHolder holder) { drawThread = new DrawThread(getHolder()); drawThread.setRunning(true); drawThread.start(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; drawThread.setRunning(false); while (retry) { try { drawThread.join(); retry = false; } catch (InterruptedException e) { } } } class DrawThread extends Thread { private boolean running = false; private SurfaceHolder surfaceHolder; private int height; private int width; public DrawThread(SurfaceHolder surfaceHolder) { this.surfaceHolder = surfaceHolder; } public void setRunning(boolean running) { this.running = running; } @SuppressWarnings("deprecation") public void MyScreenSize() { Point size = new Point(); WindowManager w = getWindowManager(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { w.getDefaultDisplay().getSize(size); width = size.x; height = size.y; } else { Display d = w.getDefaultDisplay(); width = d.getWidth(); height = d.getHeight(); } } public void run() { Canvas canvas; while (running) { canvas = null; try { canvas = surfaceHolder.lockCanvas(null); if (canvas == null) continue; canvas.drawColor(Color.GREEN); // настройка кисти // красный цвет p.setColor(Color.WHITE); // толщина линии = 10 p.setStrokeWidth(10); // рисуем точку (50,50) canvas.drawPoint(50, 50, p); // рисуем линию от (100,100) до (500,50) canvas.drawLine(100,100,500,50,p); // рисуем круг с центром в (100,200), радиус = 50 canvas.drawCircle(100, 200, 50, p); // рисуем прямоугольник // левая верхняя точка (200,150), нижняя правая (400,200) canvas.drawRect(height, 150, width, 200, p); // настройка объекта Rect // левая верхняя точка (250,300), нижняя правая (350,500) rect.set(250, 300, 350, 500); // рисуем прямоугольник из объекта rect canvas.drawRect(rect, p); } finally { if (canvas != null) { surfaceHolder.unlockCanvasAndPost(canvas); } } } } } } } 

When changing specific coordinates of points (as was the case in the textbook), I get nothing from the data of this method, namely, the square is not drawn at all. Eclipse does not detect errors. It seems to me that the error is in this method.

  • Permission code is correct. Apparently, it's not right to draw a square ... - Vladyslav Matviienko
  • Checked, drawn correctly, as I said, if you specify the specific numbers in the parameter of the square, then it is quietly drawn - Roman Vasiliev
  • And where is the call to MyScreenSize ()? Add it to the stream constructor. In general, the dimensions here must be taken from the public void method SurfaceChanged (SurfaceHolder holder, int format, int width, int height) {} - Deadkenny
  • And where is the flow constructor? - Roman Vasilyev
  • public DrawThread (SurfaceHolder surfaceHolder) {this.surfaceHolder = surfaceHolder; } - Deadkenny

3 answers 3

Usually the screen size I take is this:

 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 

Helps with centering windows, I think, will help here. Then just use the getHeight () and getWidth () methods.

  • I forgot to say, I need it on Android - Roman Vasilyev
  • one
    And if so? Display display = ((WindowManager) getSystemService (WINDOW_SERVICE)). GetDefaultDisplay (); - Yuri_Prime pm
  • Still there is no square, can I have problem modifiers or do I need an argument in brackets? - Roman Vasilyev
  • Maybe something is wrong with finding a square? And I see you have suppressed Warning, that the Deprecated method is quite possibly the problem. Try to run the code step by step, see where there are any values, what it does - Yuri_Prime
  • I took deprecative because api does not allow to use a newer one - Roman Vasilyev
  Point size = new Point(); WindowManager w = getWindowManager(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { w.getDefaultDisplay().getSize(size); mWindowWidth = size.x; mWindowHeight = size.y; } else { Display d = w.getDefaultDisplay(); mWindowWidth = d.getWidth(); mWindowHeight = d.getHeight(); } 

In mWindowWidth, the width in mWindowHeight is the height.

  • It seems I found where the problem is, or the field does not want to give the parameters of the square the value of the variable, or the variable itself does not give the value to the field. Why I don’t know. Help me fix, the code for the whole class is posted on the topic - Roman Vasilyev

It may help you:

 import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.util.DisplayMetrics; import android.widget.Toast; public class ScreenInfo { private final String TAG = ScreenInfo.class.getSimpleName(); public static final String DENSITY_HIGH = "DENSITY_HIGH"; public static final String DENSITY_MEDIUM = "DENSITY_MEDIUM"; public static final String DENSITY_LOW = "DENSITY_LOW"; public static final String DENSITY_UNKNOWN = "DENSITY_UNKNOWN"; public static void getScreenType(Activity activity, Context context){ if ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) { Toast.makeText(context, "Large screen", Toast.LENGTH_LONG).show();} else if ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) { Toast.makeText(context, "Normal sized screen", Toast.LENGTH_LONG).show(); } else if ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) { Toast.makeText(context, "Small sized screen", Toast.LENGTH_LONG).show(); } else { Toast.makeText(context, "Screen size is neither large, normal or small", Toast.LENGTH_LONG).show(); } } public static int getDensity(Activity activity, Context context){ System.out.println(" TEST DENSITY FROM CONTEXT : "+context.getResources().getDisplayMetrics().density); // Determine density DisplayMetrics metrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); int density = metrics.densityDpi; if (density == DisplayMetrics.DENSITY_HIGH) { Toast.makeText(context, "DENSITY_HIGH... Density is " + String.valueOf(density), Toast.LENGTH_LONG).show(); return DisplayMetrics.DENSITY_HIGH; } else if (density == DisplayMetrics.DENSITY_MEDIUM) { Toast.makeText(context, "DENSITY_MEDIUM... Density is " + String.valueOf(density), Toast.LENGTH_LONG).show(); return DisplayMetrics.DENSITY_MEDIUM; } else if (density == DisplayMetrics.DENSITY_LOW) { Toast.makeText(context, "DENSITY_LOW... Density is " + String.valueOf(density), Toast.LENGTH_LONG).show(); return DisplayMetrics.DENSITY_LOW; } else { Toast.makeText( context, "Density is neither HIGH, MEDIUM OR LOW. Density is " + String.valueOf(density), Toast.LENGTH_LONG).show(); return -1; } } public static void getPexelSize(Activity activity, Context context){ DisplayMetrics displaymetrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int ht = displaymetrics.heightPixels; int wt = displaymetrics.widthPixels; System.out.println("Screen size: " + wt +"/" + ht + " px"); Toast.makeText(context, "Screen size: " + wt +"/" + ht + " px", Toast.LENGTH_LONG).show(); } public static int getWidthPixels(Activity activity, Context context){ DisplayMetrics displaymetrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int wt = displaymetrics.widthPixels; return wt; } public static int getHeightPixels(Activity activity, Context context){ DisplayMetrics displaymetrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int ht = displaymetrics.heightPixels; return ht; } // Ширины экрана в dp public static int getSwDp(Activity activity){ DisplayMetrics displaymetrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int wt = displaymetrics.widthPixels; int swDp = (int) ScreenHelper.convertPixelsToDp(wt, activity); return swDp; } // Высота экрана в dp public static int getShDp(Activity activity){ DisplayMetrics displaymetrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int ht = displaymetrics.heightPixels; int shDp = (int) ScreenHelper.convertPixelsToDp(ht, activity); return shDp; } } 

ScreenHelper.java

 public class ScreenHelper { private final String TAG = ScreenHelper.class.getSimpleName(); /** * This method converts dp unit to equivalent pixels, depending on device density. * * @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels * @param context Context to get resources and device specific display metrics * @return A float value to represent px equivalent to dp depending on device density */ public static float convertDpToPixel(float dp, Context context){ Resources resources = context.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); float px = dp * (metrics.densityDpi / 160f); return px; } /** * This method converts device specific pixels to density independent pixels. * * @param px A value in px (pixels) unit. Which we need to convert into dp * @param context Context to get resources and device specific display metrics * @return A float value to represent dp equivalent to px value */ public static float convertPixelsToDp(float px, Context context){ Resources resources = context.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); float dp = px / (metrics.densityDpi /160f); return dp; } }