1

I am drawing an Arc using canvas. On my device(1080 * 1920) it looks like good, but on my friend device(720 * 1280) the radius of Arc increased.

I am setting Height and Width based on device Screen Height and width. So the Height and width for device I am getting different for different device. But Size of Arc drawn is of different size.

Please help me on this. Thanks in advance.

    @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            // Get Screen Width in Pixel
            int width = Helper.getScreenWidth(context);
            // Get Screen Height in Pixel
            int height = Helper.getScreenHeight(context);
            // Get Device Density
            int density = Helper.getDeviceDensity(context);
            setMeasuredDimension(width, height / density);
        }

/**
     * Get Screen Height
     * @param context context
     * @return int
     */
public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        int height = metrics.heightPixels;
        return height;
    }

    /**
     * Get Screen Width
     * @param context context
     * @return int
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        int width = metrics.widthPixels;
        return width;
    }

    /**
     * Get Device Screen Density
     * @param context context
     * @return int
     */
    public static int getDeviceDensity(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        int density = (int) metrics.density;
        return density;
    }
Sanni Raj
  • 127
  • 1
  • 9

1 Answers1

0

Use dp(device pixels) that way you don't have to handle the logic for different screen sizesConvert from dp to pixel:

public int dpToPx(int dp) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));       
    return px;
}

So wherever you are passing raw ints for width and height instead pass dpToPx(yourRawInt);

For more information on converting from dp to px and px to dp check this answer

Community
  • 1
  • 1
Bhargav
  • 8,118
  • 6
  • 40
  • 63