How can I set a polygon (which would be specified by a collection of points) to transparent using a PNG image on Android?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In order to accomplish this, you would have to first get a reference to the resource from a
BitmapFactory: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 pixelColorto 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 thesetPixels()method.Note that this assumes that your PNG file is mutable. You will get an
IllegalStateExceptionotherwise.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:
Δ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:
Yin thegetPixel()method until you collide with another user-drawn vertex, changing the pixels to transparent as you go usingsetPixel()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
booleanto maintain the state) as it is possible for polygons to “curve around” and come back into the column you are parsing.