user1800819
user1800819

Reputation: 55

Android bitmap with transparent region

How can I set a polygon (which would be specified by a collection of points) to transparent using a PNG image on Android?

Upvotes: 2

Views: 933

Answers (1)

Squagem
Squagem

Reputation: 734

In order to accomplish this, you would have to first get a reference to the resource from a BitmapFactory:

Bitmap my_image = BitmapFactory.decodeResource(getResources(), R.drawable.[your_image]);

Then, you would have to use the setPixels()method to define the region on the PNG that are to be made transparent. Transparency, I believe, is achieved my setting the pixel Color to 0.

Deriving the polygon would be some computation that you would have to do in your application, followed by passing the dimensions of the polygon into the setPixels() method. See this link taken from the Android developer documents for an idea on how to use the setPixels() method.

Note that this assumes that your PNG file is mutable. You will get an IllegalStateException otherwise.


Deriving The Area for an N-Sided Polygon

This is where your problem gets significantly more challenging. Since you cannot use conventional area formulas (as the area has nothing to do with this example, but rather where the vertices are located), you must figure out a way to calculate the region that must be transparent yourself.

One way I can think of doing this is to test all the pixels below a part of the user-drawn line and mark them as transparent until an intersection is met, and repeating this until the bottom of the image is reached. See this drawing for reference:

enter image description here

ΔX here, is an arbitrarily-defined pixel length that can be either increased to improve accuracy, or decreased to improve performance. The process of deriving this transparency would be as follows:

  1. Obtain the value farthest to the left that is part of a vertex a user draws;
  2. Progress down the image (by decreasing the value of Y in the getPixel() method until you collide with another user-drawn vertex, changing the pixels to transparent as you go using setPixel() and passing in your current coordinates;
  3. When you collide with another vertex, stop changing the transparency of the pixels, but continue to parse down the column;
  4. Again, if you reach another vertex, begin marking the following pixels as transparent;
  5. Repeat this until you get to the bottom of the image;
  6. Increment the X value by the constant ΔX that you predefined and repeat this on the next column.

Note that it is important that you toggle between setting the transparency and not setting transparency (you could use a boolean to maintain the state) as it is possible for polygons to "curve around" and come back into the column you are parsing.

Upvotes: 2

Related Questions