Set letter spacing to drawTextOnPath

3k Views Asked by At

I am using following code to make a spinner wheel.

@Override
    public void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);

        for (int i = 0; i < segmentColors.length; i ++)
        {
            drawDataSet(canvas, i);
        }

        canvas.drawCircle(getWidth()/2, getHeight()/2, getWidth() - getWidth()/2 - dpToPx(5), mTransparentCirclePaint);
    }


protected void drawDataSet(Canvas canvas, int position)
    {
        int color = segmentColors[position];
        float mainArcAngle = ((float) 360/ (float)segmentColors.length);

        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);

        if ( position%2 == 0)
            paint.setColor(color);
        else
            paint.setColor(Color.parseColor("#009f2f"));

        RectF rect = new RectF(0, 0, getWidth(), getWidth());
        canvas.drawArc(rect, (mainArcAngle * position), mainArcAngle, true, paint);

        TextPaint mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        mTextPaint.setColor(Color.BLACK);
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTypeface(Typeface.MONOSPACE);
        mTextPaint.setTextAlign(Paint.Align.CENTER);
        mTextPaint.setTextSize(18f);

        Path path = new Path();
        path.addArc(rect, (mainArcAngle * position), mainArcAngle);

        //PathMeasure pm = new PathMeasure(path, false);
        //DynamicLayout layout = new DynamicLayout(values[position], values[position], mTextPaint, (int) pm.getLength(), Layout.Alignment.ALIGN_CENTER, 1, 0, true);
        //canvas.save();
        //layout.draw(canvas);
        //canvas.restore();
        canvas.drawTextOnPath(values[position], path, 0 , getWidth() / 6 , mTextPaint );
    }

The text that is written inside the arc is a bit compressed because of small spacing. How can I make it multiline or increase letter spacing?

1

There are 1 best solutions below

4
On

Starting from API 21 you can use Paint#setLetterSpacing(float):

Set the paint's letter-spacing for text. The default value is 0. The value is in 'EM' units. Typical values for slight expansion will be around 0.05. Negative values tighten text.

You may also see how TextView#setLetterSpacing() is implemented.