Search code examples
iphoneuiimagetransparencyalphablending

Alpha blending on the edges of an UIImage


I have two rectangular images: one is foreground, the other one is background. I am trying to blend the edges of the foreground image so that the foreground image looks like it is "part" of the background image. In other words, I am trying to apply a transparency effect, with the opacity of the foreground image decreasing from 100% at the center of the image down to 0% at the edges. I have found that this operation is sometimes referred by different names, such as: alpha compositing, alpha blending, edge feathering or edge transparency. Here is a more detailed description of the effect I am trying to obtain: http://en.wikipedia.org/wiki/Alpha_compositing

I have looked at the CGContext documentation, but I haven't found any function that would do that out of the box.

Is there any way to do that using CGContext or even OpenGL? Would there be a way to do it on a non-rectangular image? I know, all images are rectangular, but I mean an image with let's say, a circle in it, and a transparent area all around.


Solution

  • The CGImageCreateWithMask() function in the iOS library can do alpha blending with decreasing opacity on the edges. It's possible to get something to work by combining the code in these two links:

    http://iosdevelopertips.com/cocoa/how-to-mask-an-image.html

    Creating mask with CGImageMaskCreate is all black (iphone)

    The level of gray (from black to white) of each pixel in the mask will define the level of opacity during blending.