android - 将字母间距设置为 drawTextOnPath

标签 android android-canvas android-custom-view android-paint

我正在使用以下代码制作一个转轮。

@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 );
    }

写在圆弧内的文本由于间距小而有点压缩。我怎样才能让它多行或增加字母间距?

最佳答案

从 API 21 开始,您可以使用 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.

您也可以 see TextView#setLetterSpacing() 是如何实现的。

关于android - 将字母间距设置为 drawTextOnPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44243460/

相关文章:

android - 如何将值从一个 Activity 传递到上一个 Activity

android - 如何解决 xamarin 中的 'Theme.AppCompat.Light.NoActionBar' 错误?

android - SurfaceView 绘图在上面

android - 如何使任何 View 绘制到 Canvas 上?

Android: 查看 onDraw 从未调用过

java - 如何在绘制之前获取调整大小的自定义 View 的宽度和高度

java - 图像未保存在我的相机应用程序中

c# - 指定操作区域并验证位置是否在该区域内

android - Android (2D) Canvas 绘图管道的各个部分如何组合在一起?

android - 警报对话框生成器 : setView; custom view not showing