Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add stroke/border to transparent png image in android?

I have transparent images like shapes,letters which I'm fetch from gallery so I need to give them stroke/outline with black color, I can set border but It's set to whole bitmap like left,right,top and bottom.

Same thing we can do with photoshop is giving outerstroke to image but I want to achieve that in android.

I tried this and this It's give border, But what I want to do is like below sample image

Original Image without stroke

I want like this --> With stroke

Does this possible in android?

like image 270
a.dev Avatar asked Nov 21 '18 07:11

a.dev


People also ask

How can I edit PNG in Android?

Use Background Eraser app to edit PNG images However, if you already you have a PNG image and you want to crop or erase it further, then also you can use this app. After loading the image in Background Eraser, you will be asked to crop it. The app will then take you to the editing screen.


1 Answers

I have an temporary solution like this

int strokeWidth = 8;
Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.flower_icon);
Bitmap newStrokedBitmap = Bitmap.createBitmap(originalBitmap.getWidth() + 2 * strokeWidth, originalBitmap.getHeight() + 2 * strokeWidth, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newStrokedBitmap);
float scaleX = (originalBitmap.getWidth() + 2.0f * strokeWidth) / originalBitmap.getWidth();
float scaleY = (originalBitmap.getHeight() + 2.0f * strokeWidth) / originalBitmap.getHeight();
Matrix matrix = new Matrix();
matrix.setScale(scaleX, scaleY);
canvas.drawBitmap(originalBitmap, matrix, null);
canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_ATOP); //Color.WHITE is stroke color
canvas.drawBitmap(originalBitmap, strokeWidth, strokeWidth, null);

Firstly create a new bitmap with stroke size on left, right, bottom and top.

Secondly a little bit scale bitmap and draw scaled bitmap on newly created bitmap canvas.

Draw a color (your stroke color) with PorterDuff mode SRC_ATOP override original bitmap position with stroke color.

Finally draw your original bitmap on newly create bitmap canvas.

like image 180
Mehmet Güngören Avatar answered Sep 22 '22 11:09

Mehmet Güngören