# Opacity function applied to Graphics Objects

I think this is a stupid/banal question, but I have searched the forum and I haven't find a solution (yet).

I need to apply a variable opacity function to a graphics object (say a rectangle). For instance the rectangle would have full opacity at its center and be more transparent near its edges, or have a gradient opacity along the x values.

I tried something like this but it obviously doesn't work:

Graphics[{{ColorFunction -> (Directive[Opacity[#1]] &),
Rectangle[{0 - 0.25, -1}, {0 + 0.25, 1}]}, {Circle[]}}]


(here the unit circle is only a reference graphics object)

On the other hand a similar solution works for a Plot3D, like in the following example

Plot3D[Sin[x^2 + y^2], {x, -3, 3}, {y, -3, 3},
ColorFunction -> (Directive[Opacity[#3]] &), PlotPoints -> 40,
Mesh -> None]


but I need to apply the opacity gradient to a graphics object. I'm sure there's a simple solution but I couldn't find it.

Any help?

Are you after something like this?

Graphics[{{
Polygon[Tuples[{{0 - 0.25, -1}, {0 + 0.25, 1}}][[{1, 2, 4, 3}]],
VertexColors -> {RGBColor[0, 0, 0, 0], RGBColor[0, 0, 0, 1],
RGBColor[0, 0, 0, 1], RGBColor[0, 0, 0, 0]}]}, {Circle[]}}] I wasn't sure which way you wanted the gradient to go.

A central gradient is a bit harder. The built-in gradient has some limitations:

mask = Texture[
SetAlphaChannel[Image@SparseArray[{_, _} -> 0, {201, 201}],
Polygon[Tuples[{{0 - 0.25, -1}, {0 + 0.25, 1}}][[{1, 2, 4, 3}]],
VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}], {Circle[]}}] • I think Texture is the way to go, but for an opacity gradient the gaussian should be in the alpha channel. – Simon Woods Nov 10 '14 at 15:57
• @SimonWoods Done, I hope. I seem to be not thinking too clearly this morning.... – Michael E2 Nov 10 '14 at 16:17
• Looks right to me. – Simon Woods Nov 10 '14 at 16:20
• Thanks @Michael E2. I think that Polygon + VertexColors is the simplest way to go. This code produce the effect I wanted: Graphics[{{Polygon[{{-0.25, -1}, {0, -1}, {0, 1}, {-0.25, 1}}[[{1, 2, 3, 4}]], VertexColors -> {RGBColor[0, 0, 0, 0], RGBColor[0, 0, 0, 1], RGBColor[0, 0, 0, 1], RGBColor[0, 0, 0, 0]}]}, {Polygon[{{0, -1}, {0.25, -1}, {0.25, 1}, {0, 1}}[[{1, 2, 3, 4}]], VertexColors -> {RGBColor[0, 0, 0, 1], RGBColor[0, 0, 0, 0], RGBColor[0, 0, 0, 0], RGBColor[0, 0, 0, 1]}]}, {Circle[]}}] It seems I must use 2 polygons i/o 1 but it's ok. – Luca M Nov 10 '14 at 17:16
• @LucaM You're welcome. You shouldn't need the part [[{1,2,3,4}]]. I used [[{1,2,4,3}]] to reorder the output of Tuples. The [[{1,2,3,4}]] puts parts 1,2,3,4 in the order 1,2,3,4 -- so it does nothing. – Michael E2 Nov 10 '14 at 19:10
With[{xmin = -0.25, xmax = 0.25, n = 20},
Graphics[
{Line[{{-1, 0}, {1, 0}}],
Circle[],
Blue,
Table[
{Opacity[#],
Rectangle[
{xmin + (m - 1) (xmax - xmin)/n, -1},
{xmin + m (xmax - xmin)/n, 1}]},
{m, n}]}]] & /@
{(m - 1)/(n - 1),
1 - Abs[2 ((n - 1)/2 - (m - 1))/n],
Abs[2 ((n - 1)/2 - (m - 1))/n]} 