Рисование круга программно с помощью Android ShapeDrawable

В моем проекте есть требование динамически рисовать окружность во время выполнения. Поэтому для этой цели я использую ShapeDrawable для создания круга программно, но, к сожалению, я не смог найти какой-либо класс или методы внутри ShapeDrawable для CircleShape, вместо этого я нашел только OvalShape(), Пожалуйста, помогите мне нарисовать круг через ShapeDrawable, просто передав диаметр или радиус круга. Заранее спасибо. Любой вид настройки был бы полезен для меня, чтобы исправить свое решение.

Код, который я использую для ShapeDrawable

public static ShapeDrawable drawCircle (Context context, int width, int height, int color) {

        //////Drawing oval & Circle programmatically /////////////

        ShapeDrawable oval = new ShapeDrawable (new OvalShape ());
        oval.setIntrinsicHeight (height);
        oval.setIntrinsicWidth (width);
        oval.getPaint ().setColor (color);
        return oval;
    }

Использование кода в MainActivity.java

if(Build.VERSION.SDK_INT >= 16) {
            txtCount.setBackground (Util.drawCircle (MainActivity.this, 50, 50, getResources ().getColor (R.color.yellow)));
            txtHotelCount.setText ("20");
        }else{
            txtCount.setBackgroundDrawable (Util.drawCircle (MainActivity.this, 50, 50, getResources ().getColor (R.color.yellow)));
            txtHotelCount.setText ("20");

        }

Использование XML для TextView txtCount в моем проекте для

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:background="@color/white">

        <TextView
            android:id="@+id/txt_count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/text_grey"
            android:gravity="center"
            android:textSize="12sp"
            android:padding="2dp"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/text_grey"
            android:text="AVAILABLE"
            android:layout_marginLeft="10dp"
            android:gravity="center"
            />
    </LinearLayout>

Но все равно не повезло, даже после установки той же ширины и высоты, что и 50. Свойство ведет себя все еще как овал.

3 ответа

Решение

Дайте ту же высоту и ширину вашему TextView

<TextView
            android:id="@+id/txt_count"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:textColor="@color/text_grey"
            android:gravity="center"
            android:textSize="12sp"
            android:padding="2dp"
            />

Это слишком поздно, чтобы ответить, но надеюсь, что это поможет кому-то еще. Если вы хотите нарисовать такой круг, не беспокойтесь о 46.0%, так как это только текстовый вид.

,

public class Circle extends View {

private Paint mCircleYellow;
private Paint mCircleGray;

private float mRadius;
private RectF mArcBounds = new RectF();

public Circle(Context context) {
    super(context);

    // create the Paint and set its color

}

public Circle(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    initPaints();
}

public Circle(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

private void initPaints() {
    mCircleYellow = new Paint(Paint.ANTI_ALIAS_FLAG);
    mCircleYellow.setStyle(Paint.Style.FILL);
    mCircleYellow.setColor(Color.YELLOW);
    mCircleYellow.setStyle(Paint.Style.STROKE);
    mCircleYellow.setStrokeWidth(15 * getResources().getDisplayMetrics().density);
    mCircleYellow.setStrokeCap(Paint.Cap.SQUARE);
    // mEyeAndMouthPaint.setColor(getResources().getColor(R.color.colorAccent));
    mCircleYellow.setColor(Color.parseColor("#F9A61A"));

    mCircleGray = new Paint(Paint.ANTI_ALIAS_FLAG);
    mCircleGray.setStyle(Paint.Style.FILL);
    mCircleGray.setColor(Color.GRAY);
    mCircleGray.setStyle(Paint.Style.STROKE);
    mCircleGray.setStrokeWidth(15 * getResources().getDisplayMetrics().density);
    mCircleGray.setStrokeCap(Paint.Cap.SQUARE);
    // mEyeAndMouthPaint.setColor(getResources().getColor(R.color.colorAccent));
    mCircleGray.setColor(Color.parseColor("#76787a"));

}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);

    mRadius = Math.min(w, h) / 2f;

}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int w = MeasureSpec.getSize(widthMeasureSpec);
    int h = MeasureSpec.getSize(heightMeasureSpec);

    int size = Math.min(w, h);
    setMeasuredDimension(size, size);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Float drawUpto = 46f;


    float mouthInset = mRadius / 3f;
    mArcBounds.set(mouthInset, mouthInset, mRadius * 2 - mouthInset, mRadius * 2 - mouthInset);
    canvas.drawArc(mArcBounds, 0f, 360f, false, mCircleGray);

    canvas.drawArc(mArcBounds, 270f, drawUpto, false, mCircleYellow);


}

}

Поэтому используйте этот класс в своем XML-файле, так как он является классом представления.

 // Circle

    Paint paint = new Paint();
    paint.setColor(Color.GREEN);
    paint.setStyle(Paint.Style.STROKE);
    float x = 50;
    float y = 50;
    float radius = 20;
    canvas.drawCircle(x, y, radius, paint);
Другие вопросы по тегам