itzmebibin
itzmebibin

Reputation: 9439

draw circle and fill color in android without using canvas

I am using Android Studio 2.1.2 for creating android applications. In my application, I need to create a circle filled with red color in android view. I tried it by using a canvas like,

protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            int x = getWidth();
            int y = getHeight();
            int radius = x / 2;
            Paint paint = new Paint();
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(Color.WHITE);
            paint.setStrokeWidth(2);
            canvas.drawPaint(paint);
            paint.setColor(Color.parseColor("#CD5C5C"));
            canvas.drawCircle(x / 2, y / 2, radius, paint);
        }

And in onCreate(), I have added,

setContentView(new SampleView(this));

Where SampleView is a class which contains onDraw(). Is there any alternative way to do the same thing, without using the canvas?

Upvotes: 0

Views: 4993

Answers (3)

user5421769
user5421769

Reputation:

First you need to create custom_circle.xml in drawable.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <solid android:color="@color/red" />

</shape>

Then you can use it in layout

<LinearLayout
    android:id="@+id/button1"
    android:layout_width="20sp"
    android:layout_height="20sp"
    android:layout_gravity="center"
    android:background="@drawable/custom_circle"
    android:padding="5dp"
    android:visibility="gone" />

Upvotes: 1

Katharina
Katharina

Reputation: 1642

Create a drawable from xml like this:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#FF0000"/>
</shape>

You can also set size, and stroke in this drawable if you want to. Then add an ImageView (or whatever you want) to your layout and set the drawable to it:

<ImageView
        android:src="@drawable/your_drawable" \>

Upvotes: 1

Tushar Saha
Tushar Saha

Reputation: 2106

you can create a shape xml and assign it to linear layout

Some thing like this

   <LinearLayout
            android:background="@drawable/circle_border"
            android:layout_width="100dp"
            android:layout_height="100dp">

   </LinearLayout>



<selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="false">
         <shape android:shape="oval">
            <solid android:color="@color/red" />
         </shape>
     </item>
</selector>

this will draw a circle

Hope this helps

Upvotes: 2

Related Questions