Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View with round corners not smooth

Have a look at my code below.

ShapeDrawable shapeDrawable = new ShapeDrawable(new RectShape());
    shapeDrawable.getPaint().setColor(Color.parseColor("#5a2705"));
    shapeDrawable.getPaint().setStyle(Style.STROKE);
    shapeDrawable.getPaint().setAntiAlias(true);
    shapeDrawable.getPaint().setStrokeWidth(2);
    shapeDrawable.getPaint().setPathEffect(new CornerPathEffect(10));

I am applying this as background to my LinearLayout, but the edges are not smooth. How can I fix this?

Here is the screenshot of how it looks.

enter image description here

like image 881
Goofy Avatar asked Dec 05 '22 08:12

Goofy


2 Answers

Using a programmatically-created shape drawable as a View background results in the outer half of your stroke width getting cropped off (for reasons I don't know). Look closely at your image and you'll see that your stroke is only 1 pixel wide, even though you requested 2. That is why the corners look ugly. This effect will be much more apparent if you try a bigger stroke and radius such as 10 and 40, respectively.

Either use an XML drawable, which doesn't seem to have this problem, like in Harshit Jain's answer, or do the following if you must (or prefer to) use a programmatic solution.

Solution: Use a layer list to inset the rectangle by the amount that is being clipped (half the stroke width), like this:

float strokeWidth = 2;

ShapeDrawable shapeDrawable = new ShapeDrawable(new RectShape());
shapeDrawable.getPaint().setColor(Color.parseColor("#5a2705"));
shapeDrawable.getPaint().setStyle(Style.STROKE);
shapeDrawable.getPaint().setAntiAlias(true);
shapeDrawable.getPaint().setStrokeWidth(strokeWidth);
shapeDrawable.getPaint().setPathEffect(new CornerPathEffect(10));

Drawable[] layers = {shapeDrawable};
LayerDrawable layerDrawable = new LayerDrawable(layers);

int halfStrokeWidth = (int)(strokeWidth/2);
layerDrawable.setLayerInset(0, halfStrokeWidth, halfStrokeWidth, halfStrokeWidth, halfStrokeWidth);

Then use the layerDrawable as your background. Here is a screen shot of the result of the above code:

enter image description here

like image 86
Tenfour04 Avatar answered Dec 10 '22 11:12

Tenfour04


You can try creating a separate xml file with a layout of the rounded rectangle. Such as:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="color_here"/>
    <stroke android:width="5dp" android:color="color_here"/>
    <corners android:radius="2dp"/>
</shape>

You can tune this to your liking and use this XML file as a background in your main XML.

You can also try using 9Patch which should already come with your SDK

like image 27
Harshit Jain Avatar answered Dec 10 '22 11:12

Harshit Jain