2
$\begingroup$

Suppose we have a vector Graphics object, along with an arbitrary shape to use as a mask.

drawing =Graphics[{Point@RandomReal[{0,10},{5000,2}]}];
mask = Graphics[{Gray,Polygon[{{0, 5}, {4, 8}, {7, 8}, {9, 4}, {5, 5}, {1, 2}}]}];

input image

Is it possible to use the mask to apply an opacity change or even an opacity gradient while maintaining the vector output of the initial drawing?

This is possible using SetAlphaChannel, but creates a raster image in the process.

SetAlphaChannel[drawing, mask]

output image

$\endgroup$
  • $\begingroup$ Here's an example where this is done on a vector drawing program: on Adobe Illustrator $\endgroup$ – Musang Apr 25 '18 at 15:44
4
$\begingroup$

Here is how to do it with computational geometry and the Region* functionality:

(* all points, as coordinates *)
coords = RandomReal[{0, 10}, {5000, 2}];

(* your polygonal mask, as a Polygon object, which can be used as a Region *)
polygonMask = Polygon[{{0, 5}, {4, 8}, {7, 8}, {9, 4}, {5, 5}, {1, 2}}];

(* This generates a RegionMemberFunction object that can be applied repeatedly *)
mfun = RegionMember[polygonMask];

(* Select points within the mask *)
within = Select[coords, mfun];

(* Select points outside of the mask as the complement to the set of those within *)
outside = Complement[coords, within];

(* draw the results *)
Graphics[{Black, Point@outside, Red, Point@within}]

red within, black outside

For improved contrast, I made the points within the mask red, but you could use any Graphics styling on them.

This is the result with Opacity applied to the within set:

Graphics[{Black, Point@outside, Opacity[0.1], Point@within}]

transparent points within

$\endgroup$
  • $\begingroup$ This is a neat approach and lets me change the properties of the points themselves. Also I can generalize this from points to objects like Circle or Rectangle using e.g. RegionWithin. $\endgroup$ – Musang Apr 26 '18 at 11:57
  • $\begingroup$ @Musang Glad you like it :-) $\endgroup$ – MarcoB Apr 26 '18 at 16:16
2
$\begingroup$

You could change the mask so that it has opacity:

Show[drawing, mask /. Gray->GrayLevel[1,.7]]

enter image description here

$\endgroup$
  • $\begingroup$ I had thought of this; one drawback is that you are limited to additive effects on the points. But I see now that this accounts much more easily for objects which overlap only partially with the mask. $\endgroup$ – Musang Apr 26 '18 at 12:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.