Skip to content Skip to sidebar Skip to footer

Create Custom Convex Path Android

I wish to set a custom shape (different radius for each corner of rectangle) to my frame layout, so that views in the frame layout will clip to the shape's bounds. ViewOutline

Solution 1:

I figured it out by myself. The path is not convex because I was not drawing the path correctly. The correct path that achieve the multiple corner radius effect I wanted should be:

    // Topleft circle
    oval.set(0, 0, 2 * topLeftRadius, 2 * topLeftRadius);
    borderPath.moveTo(0, topLeftRadius);
    borderPath.arcTo(oval, -180, 90);

    borderPath.rLineTo(width - topLeftRadius - topRightRadius, 0);

    // Topright circle
    oval.set(width - 2 * topRightRadius, 0, width, 2 * topRightRadius);
    borderPath.arcTo(oval, -90, 90);

    borderPath.rLineTo(0, height - topRightRadius - bottomRightRadius);

    // Bottomright circle
    oval.set(width - 2 * bottomRightRadius, height - 2 * bottomRightRadius, width, height);
    borderPath.arcTo(oval, 0, 90);

    borderPath.rLineTo(-width + bottomRightRadius + bottomLeftRadius, 0);

    // Bottomleft circle
    oval.set(0, height - 2 * bottomLeftRadius, 2 * bottomLeftRadius, height);
    borderPath.arcTo(oval, 90, 90);

    borderPath.rLineTo(0, -height + bottomLeftRadius + topLeftRadius);

Update: Although the path is correct now, it is still not convex path, seems like customized path will not be treated as convex path.

Solution 2:

Nice that you got it working, but there are built in tools for this. Easiest is in a drawable xml:

<shapexmlns:android="http://schemas.android.com/apk/res/android"><cornersandroid:bottomLeftRadius="8dp"android:topLeftRadius="8dp"android:topRightRadius="8dp"android:bottomRightRadius="0dp" /><solidandroid:color="#fff" /></shape>

Programatically you can use the RoundRectShape class. That's also what will be inflated from above xml. In the curstructor you pass outer corner radius, line thickness and inner corner radius. You can also look at the source to see how they create a path (tip: path.addRoundRect()).

Post a Comment for "Create Custom Convex Path Android"