How to corp a picture into any shape via a template in android?

柔情痞子 提交于 2019-12-12 00:55:27

问题


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 template of a png file (already present) and it cuts the picture in that shape.


回答1:


Check out this code:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final ImageView imageViewPreview = (ImageView) findViewById(R.id.imageview_preview);
    new Thread(new Runnable() {
        @Override
        public void run() {
            final Bitmap source = BitmapFactory.decodeResource(MainActivity.this.getResources(),
                    R.drawable.source);
            final Bitmap mask = BitmapFactory.decodeResource(MainActivity.this.getResources(),
                    R.drawable.mask);
            final Bitmap croppedBitmap = cropBitmap(source, mask);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    imageViewPreview.setImageBitmap(croppedBitmap);
                }
            });
        }
    }).start();
}

private Bitmap cropBitmap(final Bitmap source, final Bitmap mask){
    final Bitmap croppedBitmap = Bitmap.createBitmap(
            source.getWidth(), source.getHeight(),
            Bitmap.Config.ARGB_8888);
    final Canvas canvas = new Canvas(croppedBitmap);
    canvas.drawBitmap(source, 0, 0, null);
    final Paint maskPaint = new Paint();
    maskPaint.setXfermode(
            new PorterDuffXfermode(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: This is the mask bitmap: And this is the result:

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



来源:https://stackoverflow.com/questions/37859494/how-to-corp-a-picture-into-any-shape-via-a-template-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!