Reputation: 55
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
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.
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:
Δ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:
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;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