Johnaudi
Johnaudi

Reputation: 257

Crop/Cut the shape of a View in android dynamically

I currently have a button template (layout) as XML, where I load it off resources in my code and dynamically create the button.

So here's the question, is there any possible way to crop/cut the buttons' (or any view for that matter) into a specific shape?

Let's say I have a rectangle button, am I able to cut it to create some triangular form with it? here's an example:

enter image description here

What are the possibilities on there without having to create a custom Bitmap for it? (since the XML uses specific stroke/radius stuff which wouldn't work correctly on a Bitmap)

Is it possible for it to keep its size and margins even after the cuts? I'm really interested to know.

Thanks in advance to anyone willing to help!

Upvotes: 0

Views: 1066

Answers (1)

berserk
berserk

Reputation: 2728

You can use Canvas for what you want. It will allow you to modify the view by drawing shapes, erasing some area etc.

For example, following function will return a circular cropped bitmap of the initial bitmap provided:

public Bitmap getCroppedBitmap(Bitmap bitmap) {

        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawCircle((bitmap.getWidth() / 2), (bitmap.getHeight() / 2),
                (output.getWidth() / 2), paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        canvas = null;
        paint = null;
    //  bitmap.recycle();
        return output;
    }

To convert view into bitmap, see this.

Upvotes: 1

Related Questions