Conditional coloring based on a gradient

2019-06-22 16:11发布

问题:

Please consider :

Manipulate[
Row[{
Graphics[Disk[]], 
Graphics[{
 Polygon[{{0, 0}, {3, 0}, {3, 1}, {0, 1}},
 VertexColors -> {White, Blend[{White, Blue}], 
 Blend[{White, Blue}], White}],
 Black, Thick,
 Line[{{i, 0}, {i, 1}}]}, ImageSize -> 300]}], 
{i, 0, 3}]

Using Szabolcs`s solution on Gradient Filling

How could I color the disk with the color located underneath the Black Line ?

回答1:

Here is one solution which works because the color on the left is White and the gradient is linear.

With[{max = 3, color = Blend[{White, Blue}]}, 
 Manipulate[
  Row[{Graphics[{Opacity[i/max], color, Disk[]}], 
    Graphics[{Polygon[{{0, 0}, {max, 0}, {max, 1}, {0, 1}}, 
       VertexColors -> {White, color, color, White}], Black, Thick, 
      Line[{{i, 0}, {i, 1}}]}, ImageSize -> 300]}], {i, 0, max}]]


If you had two different colors for each end (i.e., something other than White), the Opacity approach won't work. Instead, you can use the optional blending fraction argument to Blend the colors in the desired proportion. Here's an example:

With[{max = 3, color1 = Red, color2 = Green}, 
 Manipulate[
  Row[{Graphics[{Blend[{color1, color2}, i/max], Disk[]}], 
    Graphics[{Polygon[{{0, 0}, {max, 0}, {max, 1}, {0, 1}}, 
       VertexColors -> {color1, color2, color2, color1}], Black, 
      Thick, Line[{{i, 0}, {i, 1}}]}, ImageSize -> 300]}], {i, 0, 
   max}]]



回答2:

If you need to do this for a blend of colours other than something and white, Opacity won't be suitable. You could instead stay closer to Szabolcs' original solution using the second argument to Blend like so:

skyBlue = Blend[{White,Blue}];
Manipulate[ Row[{ Graphics[{Blend[{White,skyBlue},i/3], Disk[]}],  
 Graphics[{  Polygon[{{0, 0}, {3, 0}, {3, 1}, {0, 1}},  
 VertexColors -> {White, skyBlue,   
 skyBlue, White}],  Black, Thick,  
 Line[{{i, 0}, {i, 1}}]}, ImageSize -> 300]}],  {i, 0, 3}]

I have divided i by 3 because that parameter is meant to vary between 0 and 1.