按多边形区域裁剪图像

时间:2013-04-12 10:30:38

标签: android image image-processing crop

我想通过多边形区域裁剪图像,但是找不到可以制作它的任何库。 OpenCV对于这个小东西来说太大了。 JJIL [enter link description here]只裁剪矩形区域。 也许你有任何想法我怎么能实现它?谢谢你的帮助!

enter image description here enter image description here

FOR Nidhi: 尝试这样的东西,如果不起作用 - 为路径创建另一个画布,然后从中获取Bitmap(用于遮罩),并将此遮罩位图应用于初始画布而不是drawPath。

Bitmap obmp = BitmapFactory.decodeResource(getResources(), R.drawable.image1);
Bitmap resultImg = Bitmap.createBitmap(obmp.getWidth(), obmp.getHeight(), Bitmap.Config.ARGB_8888);
Bitmap maskImg = Bitmap.createBitmap(obmp.getWidth(), obmp.getHeight(), Bitmap.Config.ARGB_8888);

Canvas mCanvas = new Canvas(resultImg);
Canvas maskCanvas = new Canvas(maskImg);

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL);;
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));

Path path = new Path();
path.moveTo(view.mx,view.my);
path.lineTo(view.x1,view.y1);
path.lineTo(view.x2,view.y2 );
path.lineTo(view.x3,view.y3);
path.lineTo(view.x4,view.y4);
path.close();

maskCanvas.drawPath(path, paint);   
mCanvas.drawBitmap(obmp, 0, 0, null);
mCanvas.drawBitmap(maskImg, 0, 0, paint);

2 个答案:

答案 0 :(得分:2)

感谢Eddy_Em,我通过使用PorterDuffXfermode实现了这一点。 Good example

答案 1 :(得分:0)

这是一个有效的Kotlin示例,该示例根据路径将图像裁剪和共享为多边形

  private fun createBitmap() {
    var bitmap = BitmapFactory.decodeResource(resources, R.drawable.gr)
    val mutableBitmap: Bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true)

    val bitmap2 = Bitmap.createBitmap(400, 400, Bitmap.Config.ARGB_8888)
    val polyCanvas = Canvas(bitmap2)
    val canvas = Canvas(mutableBitmap)
   
    var paint = Paint()
    paint.strokeWidth = 9f
   
    val path = Path()
    path.moveTo(150f, 0f)
    path.lineTo(230f, 120f)
    path.lineTo(290f, 160f)
    path.lineTo(150f, 170f)
    path.lineTo(70f, 200f)
    path.lineTo(150f, 0f)
    polyCanvas.drawPath(path, paint)
    paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN);
    polyCanvas.drawBitmap(mutableBitmap, 0f, 0f, paint)

    imageView.setImageBitmap(bitmap2)

  }