Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically create a round cornered border using ShapeDrawable in android?

I need to create a border with rounded corners programatically by extending ShapeDrawable. I need to have a black border with rounded corners with the pixels on the outside being white and the inner pixels being transparent. The code I have at the moment has multiple problems, of which are that it does not create a smooth corner that is the same thickness as the border and that the outer pixels of the border are transparent and not white.

Here is a picture of the corners I am currently getting corner

Here is the code where I am passing Color.TRANSPARENT for 'fill' in the constructor:

public class CustomShape extends ShapeDrawable {
 private final Paint fillpaint, strokepaint;
public CustomShape(int fill, int strokeWidth,int radius) {

    super(new RoundRectShape(new float[] { radius, radius, radius, radius, radius, radius, radius, radius }, null, null));
    fillpaint = new Paint(this.getPaint());
    fillpaint.setColor(fill);
    strokepaint = new Paint(fillpaint);
    strokepaint.setStyle(Paint.Style.STROKE);
    strokepaint.setStrokeWidth(strokeWidth);
    strokepaint.setColor(Color.BLACK);
}



@Override
protected void onDraw(Shape shape, Canvas canvas, Paint paint) {
    shape.draw(canvas, fillpaint);
    shape.draw(canvas, strokepaint);
}

}

like image 727
user1592512 Avatar asked Nov 24 '13 05:11

user1592512


People also ask

How do I curve a border in Android Studio?

This in-built feature makes rounded corners very easy to implement. It works on any view or layout and supports proper clipping. Create a rounded shape drawable and set it as your view's background: android:background="@drawable/round_outline" Clip to outline in code: setClipToOutline(true)

How do you add corner radius in XML?

xml version = "1.0" encoding = "utf-8" ?> Step 5: Now go to the activity_main. xml file and add an attribute to that TextView, for which you want to add rounded corners. The attribute is android: background=”@drawable/rounded_corner_view”.


1 Answers

If you need evenly rounded corners (and from your example it seems you do) you can simply use GradentDrawable with a solid color

GradientDrawable gd = new GradientDrawable();
gd.setColor(Color.RED);
gd.setCornerRadius(10);
gd.setStroke(2, Color.WHITE);

view.setBackground(gd);

GradientDrawable documentation can be found here.

Edit: For each corner separately

You can specify radius of each corner separately using setCornerRadii (float[] radii) method. "For each corner, the array contains 2 values, [X_radius, Y_radius]. The corners are ordered top-left, top-right, bottom-right, bottom-left. This property is honored only when the shape is of type RECTANGLE.

It is recommended to invoke mutate() before changing this property.

like image 142
SGal Avatar answered Oct 04 '22 10:10

SGal