jeudi 13 août 2015

How show text in centre of each rectangle using onDraw

I'm trying to create a text view (black colour) containing numbers 1 to 7 (each number on top and in the centre of each grey rectangle - just like the image I've drawn below) but I'm not sure what properties I need to add in order to achieve this. I believe the code needs to go in the loop section but I don't what code. What can be done so that a number appears centralised in each grey rectangle?

desired outcome

enter image description here

current outcome

enter image description here

public class RectangleTextView extends View {
    private final Paint mBackPaint = new Paint();
    private final Paint mRedPaint = new Paint();
    private int mSideRectWidth = 10;

    public RectangleTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mBackPaint.setColor(Color.BLACK);
        mRedPaint.setColor(Color.RED);
    }

    @Override protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (getWidth() == 0)
            return;

        //draw grey boxes
        setBackgroundColor(Color.parseColor("#808080"));
        int boxWidth = getWidth() / 7;

        //draw black lines and/or draw text in centre of each rectangle
        for (int i = 0; i < 7; i++) {
            canvas.drawLine(mSideRectWidth + boxWidth * i, 0, mSideRectWidth + boxWidth * i, getHeight(), mBackPaint);
        canvas.drawText(?);
        }

        //draw text in centre of each rectangle
        ?

        //draw left end rectangle
        canvas.drawRect(0, 0, mSideRectWidth, getHeight(), mRedPaint);

        //draw right end rectangle
        canvas.drawRect(getWidth() - mSideRectWidth, 0, getWidth(), getHeight(), mRedPaint);
    }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire