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