Jakub Wisniewski
Jakub Wisniewski

Reputation: 2249

how to clip circle in xml

I need to create semi-circle in xml. I have came across clip, but I am unsure how to use it.

This is my circle_view drawable:

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

<solid
    android:color="#666666"/>

<size
    android:width="120dp"
    android:height="120dp"/>
</shape>

And this is what I tried with clip:

<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="http://schemas.android.com/apk/res/android"
  android:clipOrientation="vertical"
  android:drawable="@drawable/circle_view"
  android:gravity="top"/>

But the result is nothing. How can I use clip properly in pure xml?

Upvotes: 3

Views: 2896

Answers (1)

Sathish Kumar J
Sathish Kumar J

Reputation: 4335

You can implement you own Drawable. But that cannot be inflated from XML. You need to set the drawable from code using

 View.setBackgroundDrawable();

Try this for sample implementation to draw a semi circle using drawable.

public class SemiCircleDrawable extends Drawable {

private Paint paint;
private RectF rectF;
private int color;
private Direction angle;

public enum Direction
{
    LEFT,
    RIGHT,
    TOP,
    BOTTOM
}

public SemiCircleDrawable() {
    this(Color.BLUE, Direction.LEFT);
}

public SemiCircleDrawable(int color, Direction angle) {
    this.color = color;
    this.angle = angle;
    paint = new Paint();
    paint.setColor(color);
    paint.setStyle(Style.FILL);
    rectF = new RectF();
}

public int getColor() {
    return color;
}

/**
 * A 32bit color not a color resources.
 * @param color
 */
public void setColor(int color) {
    this.color = color;
    paint.setColor(color);
}

@Override
public void draw(Canvas canvas) {
    canvas.save();

    Rect bounds = getBounds();

    if(angle == Direction.LEFT || angle == Direction.RIGHT)
    {
        canvas.scale(2, 1);
        if(angle == Direction.RIGHT)
        {
            canvas.translate(-(bounds.right / 2), 0);
        }
    }
    else
    {
        canvas.scale(1, 2);
        if(angle == Direction.BOTTOM)
        {
            canvas.translate(0, -(bounds.bottom / 2));
        }
    }


    rectF.set(bounds);

    if(angle == Direction.LEFT)
        canvas.drawArc(rectF, 90, 180, true, paint);
    else if(angle == Direction.TOP)
        canvas.drawArc(rectF, -180, 180, true, paint);
    else if(angle == Direction.RIGHT)
        canvas.drawArc(rectF, 270, 180, true, paint);
    else if(angle == Direction.BOTTOM)
        canvas.drawArc(rectF, 0, 180, true, paint);
}

@Override
public void setAlpha(int alpha) {
    // Has no effect
}

@Override
public void setColorFilter(ColorFilter cf) {
    // Has no effect
}

@Override
public int getOpacity() {
    // Not Implemented
    return 0;
}

}

Credits : #Vivek Khandelwal

Upvotes: 2

Related Questions