简体   繁体   中英

Draw Text inside Arc CustomView

i am trying to draw text inside of arc . code is as follows

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

}

how i can draw text which is centre of radius ... what happening is on different device text is not coming in centre of radius 图片

in given image i want canvas.drawtext should where Text is present

Add this line to your onDraw()

mPaint1.setTextAlign(Paint.Align.CENTER);

then the x parameter in drawText can just be the center x of the circle. You should be able to use mRect.centerX() to get that value.

You should use mRect.centerY() for the y value too, except it needs to be adjusted. The y parameter is actually the text baseline, so if you want to center vertically as well as horizontally, you will have to check some values in the paint's FontMetrics to see how much to lower your y value so that the text looks centered vertically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM