views:

194

answers:

1

I have an image and a convex polygon defined by an array of x,y coordinates.

How would I go about getting a Texture2D representation of the part of the image encompassed by the polygon?

Basically I just need a texture from the image with the part outside the polygon made transparent.

If the resultant texture were also clipped to the width and height of the polygon I'd do backflips.

Any pointers/snippets would be appreciated. Thank you!

+1  A: 

Interestingly, your question is tagged with both cocos2d and opengl, but I'll give an OpenGL-centric answer here. Rather than creating a new texture object to achieve the desired effect, I think you'd want to use the stencil buffer. The procedure would look like this:

  1. When creating your FBO, attach a stencil buffer to it.
  2. Clear the stencil buffer.
  3. Turn off writes to the color and depth buffers; turn on writes to stencil.
  4. Render the polygon and don't bother with texturing.
  5. Re-enable writes to the color and depth buffers; turn on stencil testing.
  6. Render a textured quad that corresponds to the bounding box of your polygon.

The iPhone 3GS and the iPhone simulator both support an 8-bit stencil buffer. For older iPhones, you might be able to do a similar trick with the framebuffer's alpha component rather than the stencil buffer...

prideout
spent most of the week thus far struggling with this so thank you for the help! presently trying to decipher the alpha component approach you mentioned. thanks again.
Monte