Skip to content Skip to sidebar Skip to footer

How To Corp A Picture Into Any Shape Via A Template In Android?

I wanted to know if it was possible to crop a picture to any other shape not just square, rectangle or circle. Basically what I am looking for is that, the user can select a templ

Solution 1:

Check out this code:

publicclassMainActivityextendsAppCompatActivity {

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    finalImageViewimageViewPreview= (ImageView) findViewById(R.id.imageview_preview);
    newThread(newRunnable() {
        @Overridepublicvoidrun() {
            finalBitmapsource= BitmapFactory.decodeResource(MainActivity.this.getResources(),
                    R.drawable.source);
            finalBitmapmask= BitmapFactory.decodeResource(MainActivity.this.getResources(),
                    R.drawable.mask);
            finalBitmapcroppedBitmap= cropBitmap(source, mask);
            runOnUiThread(newRunnable() {
                @Overridepublicvoidrun() {
                    imageViewPreview.setImageBitmap(croppedBitmap);
                }
            });
        }
    }).start();
}

private Bitmap cropBitmap(final Bitmap source, final Bitmap mask){
    finalBitmapcroppedBitmap= Bitmap.createBitmap(
            source.getWidth(), source.getHeight(),
            Bitmap.Config.ARGB_8888);
    finalCanvascanvas=newCanvas(croppedBitmap);
    canvas.drawBitmap(source, 0, 0, null);
    finalPaintmaskPaint=newPaint();
    maskPaint.setXfermode(
            newPorterDuffXfermode(PorterDuff.Mode.DST_OUT));
    canvas.drawBitmap(mask, 0, 0, maskPaint);
    return croppedBitmap;
}

}

The main function is the "cropBitmap" function. Basically it receives two bitmaps, a source and a mask, and then it "crops" the source bitmap using the mask's shape. This is my source bitmap: Source bitmap This is the mask bitmap: Mask bitmap And this is the result: Result

Also, check out this great presentation, this might help you too: Fun with Android shaders and filters

Post a Comment for "How To Corp A Picture Into Any Shape Via A Template In Android?"