3

Basically I'd like to produce a graphic like this:

rectangle

That is a rectangle with rounded corners, filled with a color gradient. While Rectangle offers the RoundingRadius option that takes care of the round corners, there is no obvious way of getting the color gradient to work. Using Polygon it's easy to implement the gradient, but I can only think of very messy ways of rounding the corners. Can I have both?

Update

I just found this answer. That's very close to what I want, but that solution doesn't allow for nice edges.

murphy
  • 1,249
  • 8
  • 20

2 Answers2

4

This may be messy indeed, but it gets us scalable vector graphics:

w = 10;
r = 1.2;
h = 3.5;
dt = π/40;
pts =
  {
   {0, 0}, {w, 0},
   Sequence@@Table[{w, 0} + r { Sin[t], 1 - Cos[t]}, {t, dt, π/2 - dt, dt}],
   {w + r, r}, {w + r, h},
   Sequence@@Table[{w, h} + r { Cos[t], Sin[t]}, {t, dt, π/2 - dt, dt}],
   {w, h + r}, {0, h + r},
   Sequence@@Table[{0, h} + r { -Sin[t], Cos[t]}, {t, dt, π/2 - dt, dt}],
   {-r, h}, {-r, r},
   Sequence@@Table[{0, r} - r { Cos[t], Sin[t]}, {t, dt, π/2 - dt, dt}]
  };

Graphics[
  {
    EdgeForm[{Black, Thickness[0.02]}], 
    Polygon[pts, VertexColors -> (Blend[{White, Red}, #[[2]]/(h + r)] & /@ pts)]
  }
]

Mathematica graphics

Sjoerd C. de Vries
  • 65,815
  • 14
  • 188
  • 323
3

Using a tweaked version of my answer here and a graphics expression which draws the rectangle outline separately:

texturedShape[img_, shape_] := 
 Module[{g, p, ar, i}, g = Graphics[shape, PlotRangePadding -> 0];
  p = Polygon[AbsoluteOptions[g, PlotRange][[1, 2]] /.
    {{l_, r_}, {b_, t_}} :> {{l, b}, {l, t}, {r, t}, {r, b}},
    VertexTextureCoordinates -> {{0, 0}, {0, 1}, {1, 1}, {1, 0}}];
  ar = AbsoluteOptions[g, AspectRatio][[1, 2]];
  i = SetAlphaChannel[img, ColorNegate@Rasterize[g, ImageSize -> ImageDimensions@img]];
  {Texture[ImageData@i], p}]

With[{
  rect = Rectangle[{0, 0}, {2, 1}, RoundingRadius -> 0.2],
  tex = LinearGradientImage[{Top, Bottom} -> {Red, White}, {200, 100}]},
 Graphics[{
   (* inside  *) texturedShape[tex, rect],
   (* outline *) FaceForm[None], EdgeForm[{Thickness[0.02], Black}], rect}]]

enter image description here

Simon Woods
  • 84,945
  • 8
  • 175
  • 324