自定义视图不对齐中心

时间:2016-02-20 13:38:42

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

我正在绘制canavasarc,但有些它总是从左边开始,我应该从中间开始

  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 / 2) - mStrokeWidth, getWidth() + (mRadius / 2) - mStrokeWidth
    );
        canvas.drawArc(mRect, lastDegree, mSectionDegree, false, mPaint);

为什么这个视图总是从左边开始,即使我已经给了重力中心

float Degree = 270 + (mGap / 2);
    for (int i = 0; i < mTotalSections; i++) {

        fillColor(i);
        canvas.drawArc(mRect, Degree, mDegree, false, mPaint);
        Degree += mDegree + mGap;
        Paint mPaint1 = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint1.setStrokeWidth(1);
        mPaint1.setStyle(Paint.Style.FILL);
        mPaint1.setAntiAlias(true);
        mPaint1.setTextSize(15 * getResources().getDisplayMetrics().density);

        mPaint1.setColor(getResources().getColor(black));

        mPaint1.setTextAlign(Paint.Align.CENTER);
        canvas.drawText(text, mRect.centerX(), mRect.centerY(), mPaint1);
    }

1 个答案:

答案 0 :(得分:0)

我不确定你想做什么,但你的矩形看起来很奇怪。更像这样的矩形会更好:

 mRect = new RectF(
        0 + mStrokeWidth, 0 + mStrokeWidth, getWidth() - mStrokeWidth, getHeight - mStrokeWidth
);

但是对你想要的东西以及你的角度值的一点描述将是完美的;)。如果你提供,我会编辑我的答案。

编辑: 因此,如果您想在自定义视图中间使用圆圈,则可以执行以下操作:

 RectF mRect = new RectF(
            50 + mStrokeWidth, 50 + mStrokeWidth, getWidth() -50 - mStrokeWidth, getHeight() -50 - mStrokeWidth
    );

    canvas.drawArc(mRect, 0,360,false,paint);

结果(蓝线是我视图的限制): circle

您必须修改50以适合您的需要;)。 如果你想要一个以180度的角度粘在边缘上的弧:

RectF mRect = new RectF(
             mStrokeWidth,  mStrokeWidth, getWidth()  - mStrokeWidth, getHeight()  - mStrokeWidth
    );

    canvas.drawArc(mRect, 0,180,false,paint);

结果:

Arc

如果您需要别的东西,请告诉我。