2

I have a Bitmap inside a View. Here's my code for drawing it:

@Override protected void onDraw(Canvas canvas) {
        canvas.drawColor(0xFFCCCCCC);

        int w = mBitmap.getWidth();
        int h = mBitmap.getHeight();
        float[] mVerts = {
                0, 0,
                w * 0.8f, 0,
                0, h,
                w, h * 0.7f
        };
        canvas.drawBitmapMesh(mBitmap, 1, 1, mVerts, 0, null, 0, null);

}

and it looks like this:

enter image description here

Now, the question is:

If I have an image with some shape and transparent background how can I find a polygon, which is covering the area and will look like this:

enter image description here

And then how should I add all these points to the bitmap mesh so I can let user move them and manipulate an image like in the first example?

Makalele
  • 7,431
  • 5
  • 54
  • 81

1 Answers1

1

My rough idea is to go to every pixel and check if the color is transparent or not. We can traverse vertically to every horizontal line. In any horizontal line, we can first find the leftmost boundary point of focus image and break the loop when we find it. Now in same horizontal line, we can find the rightmost boundary point of your focus image. You can add all these boundary pixels (x,y) coordinates into your ArrayList mVerts.

Something like this -

for(int i=0;i<bitmap.getHeigth();i++){
for(int j=0;j<bitmap.getWidth();j++){
    int pixel = bitmap.getPixel(i,j);
    if(pixel != Color.TRANSPARENT){
       mVerts.add(i);
       mVerts.add(j);
       break;
    }
}

for(int j=bitmap.getWidth()-1; j>=0 ;j--){
    int pixel = bitmap.getPixel(i,j);
    if(pixel != Color.TRANSPARENT){
       mVerts.add(i);
       mVerts.add(j);
       break;
    }
}
}

You can pass this ArrayList mVerts to your canvas.drawBitmapMesh() method to extract the focus image.

You can use following to get color of any pixel. Source for this - here

int colorCode = imageView.getDrawingCache().getPixel(x, y);
Sachin Aggarwal
  • 1,095
  • 8
  • 17
  • But won't it give me thousands of points? On the image above you have only several of them. And it can be even less because tons of points will impact performance. – Makalele Aug 25 '17 at 08:46
  • @Makalele Yes I agree. You can increase the loop increment amount but then it may not always give you best result. What you need is some graphics algorithm that could detect all the sharp boundary points. You can use that algorithm with the logic I have explained above i.e. checking color of pixel is transparent or not. Thanks :) – Sachin Aggarwal Aug 25 '17 at 08:50
  • 1
    Also for performance, you can use some bitmap optimization. Since we don't need high-quality image to generate mVerts array, you can use the low-quality equivalent of your image which will give you all the coordinates. Then you can find the new pixels for your high-quality image. I hope this answer gives you a point to start with. – Sachin Aggarwal Aug 25 '17 at 08:54