2

Using the code given below we can retrieve the height and the width of a particular screen size :

    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
    float dpWidth = displayMetrics.widthPixels / displayMetrics.density;

I want to draw rectangles in a row as shown in the image. I have chosen default values for the rectangle width to be 100(in the drawRect() I have passed the difference between the right and left point to be 100, so that each rectangle is wide by 100). Each rectangle contains digits as shown in the picture. Now if the number of digits is small, the rectangles and the digits are rendered fine. But if the number of digits is large, the rectangles go outside the screen. For such a case I calculate the total width that the rectangles(including padding, commas, etc) will take, and compare it to the screen width. I am having issues with the code as the width that I get is in DP and the width that I calculate is not. How do I change the calculation of the total width covered by the rectangles, so that if this width is more than the width of the screen, I can reduce the dimensions of the rectangles, to render the rectangles within the scree.

Also, I want to render the rectangles "Centrally Aligned". How do I achieve that.

Given below is the image :

enter image description here

The code for the class is as follows :

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.StaticLayout;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;

public class CounterWidget extends View {

    private int DIGIT_SIZE = 120;
    private int TEXT_SIZE = 75;
    private int PADDING_LEFT=20;
    private int PADDING_RIGHT=20;
    private int RECT_HEIGHT=135;
    private int RECT_WIDTH=100;
    private int PADDING_BETWEEN_RECTS=10;
    private int PADDING_BETWEEN_RECTANGLE_DIGIT_HORIZONTAL=12;
    private int PADDING_BETWEEN_RECTANGLE_DIGIT_VERTICAL=25;

    private int number = 1200000, rectColor, numColor, counter, noOfCommas, totalPadding;
    private int digits[] = new int[15];
    private Paint widgetPaint, numberPaint, textPaint, commaPaint;
    private String defaultText;

    public CounterWidget(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CounterWidget, 0, 0);
        try {
            rectColor = a.getInteger(R.styleable.CounterWidget_rectColor, 0);
            numColor = a.getInteger(R.styleable.CounterWidget_numberColor, 1);
            defaultText=a.getString(R.styleable.CounterWidget_defaultText);
        } finally {
            a.recycle();
        }
        init();
    }

    private void init() {
        // Paint object for the rectangles.
        widgetPaint = new Paint();
        widgetPaint.setStyle(Paint.Style.FILL);
        widgetPaint.setAntiAlias(true);
        widgetPaint.setColor(rectColor);
        // Paint object for the number.
        numberPaint = new Paint();
        numberPaint.setAntiAlias(true);
        numberPaint.setColor(numColor);
        numberPaint.setTextSize(DIGIT_SIZE);
        // Paint object for the comma.
        commaPaint = new Paint();
        commaPaint.setAntiAlias(true);
        commaPaint.setColor(rectColor);
        commaPaint.setTextSize(DIGIT_SIZE);
        //Calculation for the total number of digits.
        int i = 0;
        while (number > 0) {
            digits[i] = number % 10;
            number = number / 10;
            i++;
        }
        counter = i - 1;
    }

    private void getNoOfCommas()
    {
        int a = counter+1;
        if(a>0&&a<=3)
            noOfCommas=0;
        else if(a>3&&a<=6)
            noOfCommas=1;
        else if(a>6&&a<=9)
            noOfCommas=2;
        else if(a>9&&a<=12)
            noOfCommas=3;
        else
            noOfCommas=4;
    }

    @Override
    protected void onDraw(Canvas canvas) {

        DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();

        float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
        float dpWidth = displayMetrics.widthPixels / displayMetrics.density;

        float pix = dpToPx(getContext(),(int) dpWidth);

        checkForWidth(pix);
        // The text passed in the layout.
        // Starting point for the rendering of the counter.
        Rect rect = new Rect(20, 20, (20+RECT_WIDTH), (20+RECT_HEIGHT)); // Calculation of the starting point.
        // Origin for rendering of the digit inside the rectangle.
        int xx = rect.left + PADDING_BETWEEN_RECTANGLE_DIGIT_HORIZONTAL;
        int yy = (rect.bottom - PADDING_BETWEEN_RECTANGLE_DIGIT_VERTICAL);
        // Origin for rendering the first comma.
        int xxx,yyy = (rect.bottom +10);

        for (int i = counter,j=0; i >= 0; i--,j++) {
            // Drawing the rectangle and using rectangle as reference, drawing the digit.
            drawColoredDigit(canvas, rect, String.valueOf(digits[i]),xx,yy);
            // Updating the reference values for the rectangle.
            rect.left += (PADDING_BETWEEN_RECTS + RECT_WIDTH);
            rect.right += (PADDING_BETWEEN_RECTS + RECT_WIDTH);
            // Updating the reference values for the digits inside the rectangle.
            xx = (rect.left+ PADDING_BETWEEN_RECTANGLE_DIGIT_HORIZONTAL);
            xxx = (rect.left - PADDING_BETWEEN_RECTS/2);

            if(((counter-j)%3==0)&&(counter!=j))
            {
                canvas.drawText(",",xxx,yyy,commaPaint);
                rect.left += (2*PADDING_BETWEEN_RECTS);
                rect.right += (2*PADDING_BETWEEN_RECTS);
                xx = (rect.left + PADDING_BETWEEN_RECTANGLE_DIGIT_HORIZONTAL);
            }
        }
    }

    private void drawColoredDigit(Canvas canvas, Rect rect, String digit, int xx, int yy) {
        canvas.drawRect(rect, widgetPaint);
        canvas.drawText(digit, xx, yy, numberPaint);
    }

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

    public static float convertPixelsToDp(float px, Context context){
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        float dp = px / (metrics.densityDpi / 160f);
        return dp;
    }

        private void checkForWidth(float width)
        {
        getNoOfCommas();
        totalPadding=(PADDING_BETWEEN_RECTS*(counter-1))+(noOfCommas*20)+PADDING_LEFT+PADDING_RIGHT;
        int x = ((counter+1)*RECT_WIDTH)+totalPadding;
        if( width<(x)) {
            DIGIT_SIZE /= 3;
            TEXT_SIZE /= 3;
            RECT_HEIGHT-=30;
            RECT_WIDTH-=30;
            PADDING_BETWEEN_RECTANGLE_DIGIT_VERTICAL/=2;
            PADDING_BETWEEN_RECTANGLE_DIGIT_HORIZONTAL/=2;
        }
        else {
            Continue using the same dimensions.
        }
    }
    public int convertToDp(int input)
    {
        float scale = getResources().getDisplayMetrics().density;
        return (int) (input * scale + 0.5f);
    }}

In the above code, I was trying to shrink the rectangles and the text within the rectangles.

Arjun Issar
  • 672
  • 4
  • 13
  • 32
  • Could you please post a code of your class? – Paul Freez Apr 08 '15 at 10:41
  • I have added the code to the question. The values have been hardcoded as of now. But for making the code work for all phone sizes, I want to choose the default values based on the screen size. Could that be achieved too? – Arjun Issar Apr 08 '15 at 11:06
  • Also, another approach to this problem could be, instead of shrinking the size of the rectangles, the view can be made scrollable. How can this custom view be made scrollable? – Arjun Issar Apr 08 '15 at 11:20
  • Hey, is your question still in power? – Paul Freez Apr 10 '15 at 05:35

0 Answers0