【问题标题】:Draw Text inside Arc CustomView在 Arc CustomView 中绘制文本
【发布时间】:2015-12-29 13:53:10
【问题描述】:

我正在尝试在 arc 内绘制文本。代码如下

  public Round(Context context, int totalSections, int activeSections, String mText) {
    super(context);
    int dpi = context.getResources().getDisplayMetrics().densityDpi;
    float x = 0.25f;
    final float radius = x * (new Float(dpi));
    mRadius = Math.round(radius) + 20;
    mRect = new RectF(
            getWidth() + mStrokeWidth, getWidth() + mStrokeWidth, getWidth() + mRadius - mStrokeWidth, getWidth() + mRadius - mStrokeWidth
    );
    text = mText;
    mTotalSections = totalSections;
    mActiveSections = activeSections;
    mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mPaint.setStrokeWidth(mStrokeWidth);
    mPaint.setStyle(Paint.Style.STROKE);
    mSectionDegree = 360 / mTotalSections;
    mSectionDegree -= mGap;
}


public void setmActiveSections(int mActiveSections) {
    this.mActiveSections = mActiveSections;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    float lastDegree = 270 + (mGap / 2);
    for (int i = 0; i < mTotalSections; i++) {
        if (i < mActiveSections) {
            mPaint.setColor(Color.GREEN);
        } else {
            mPaint.setColor(Color.GRAY);
        }
        canvas.drawArc(mRect, lastDegree, mSectionDegree, false, mPaint);

        lastDegree += mSectionDegree + mGap;
    }
    Paint mPaint1 = new Paint(Paint.ANTI_ALIAS_FLAG);
    mPaint1.setStrokeWidth(1);
    mPaint1.setStyle(Paint.Style.STROKE);
    mPaint1.setTextSize(15);
    mPaint1.setColor(getResources().getColor(R.color.red));

    canvas.drawText(text, 20,30, mPaint1);

}

我如何绘制半径中心的文本...发生在不同设备上的文本不在半径中心

在给定的图像中,我希望 canvas.drawtext 应该出现在 Text 的位置

【问题讨论】:

    标签: android canvas android-canvas android-custom-view


    【解决方案1】:

    将此行添加到您的onDraw()

    mPaint1.setTextAlign(Paint.Align.CENTER);
    

    那么drawText 中的x 参数可以是圆的中心x。您应该可以使用mRect.centerX() 来获取该值。

    你也应该使用mRect.centerY() 作为 y 值,除非它需要调整。 y 参数实际上是文本基线,因此,如果您想垂直居中和水平居中,则必须检查绘图 FontMetrics 中的一些值,以查看将 y 值降低多少以使文本看起来垂直居中.

    【讨论】:

    • 可以提供更多关于 FontMetrics 的信息吗?我应该如何设置文本大小
    • mPaint1.setTextSize(10 * getResources().getDisplayMetrics().density);但这在一些大型设备中提供了像素
    • 您可能需要发布更多图像示例,因为乘以显示密度因子应该可以正常工作。另一种方法可能是说“我希望文本大小为圆圈大小的 1/6”并将文本大小设置为 mRect.height() / 6。我不确定你对文本的确切要求是什么,所以我不能肯定。
    • 问题是圆形即将完美,但有很大的矩形,所以圆形从左边开始,然后是空的空间,因为那个矩形采取了我们只能做圆形而不是矩形的任何方式..所以基本上圆形在矩形中,其中矩形大小大于圆形,我们可以使它相同@kris larson
    猜你喜欢
    • 2012-12-03
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 1970-01-01
    相关资源
    最近更新 更多