wpf3dlineargradientbrush

Absolute scaling a LinearGradientBrush texture in WPF 3D


I've the following XAML:

    <Viewport3D>
      <Viewport3D.Camera>
        <OrthographicCamera FarPlaneDistance="100" LookDirection="0, 0,-1" UpDirection="0,1,0" NearPlaneDistance="1" Position="0,0,5" Width="10" />
      </Viewport3D.Camera>
      <ModelVisual3D>
        <ModelVisual3D.Content>
      <DirectionalLight Color="White" Direction="0,0,-1" />
        </ModelVisual3D.Content>
      </ModelVisual3D>
      <ModelVisual3D>
        <ModelVisual3D.Content>
          <GeometryModel3D>
            <GeometryModel3D.Material>
              <DiffuseMaterial>
                <DiffuseMaterial.Brush>
                  <LinearGradientBrush>
                    <GradientStop Color="Yellow" Offset="0" />
                    <GradientStop Color="Blue" Offset="1" />
                  </LinearGradientBrush>
                </DiffuseMaterial.Brush>
              </DiffuseMaterial>
            </GeometryModel3D.Material>
            <GeometryModel3D.Geometry>
              <MeshGeometry3D Positions="-1,-1,0 -1,1,0 1,1,0 1,-1,0" TriangleIndices="0,2,1 2,0,3" TextureCoordinates="0,0 .5,0, .5,.5 0,.5"/>
          </GeometryModel3D.Geometry>
        </GeometryModel3D>
      </ModelVisual3D.Content>
    </ModelVisual3D>
  </Viewport3D>

What I want is for only half the gradient to be used (because my texture coordinates only go from 0 to 0.5). Unfortunately, the LinearGradientBrush is stretching to fill the geometry regardless of the texture coordinates used.

You can fix this with TileBrush derived brushes using ViewportUnits="Absolute", but I've no idea how to fix it for a LinearGradientBrush. Any ideas?


Solution

  • Use the LinearGradientBrush on a RectangleGeometry of the full size, and use that in a DrawingBrush:

    <DrawingBrush ViewportUnits="Absolute">
        <DrawingBrush.Drawing>
           <GeometryDrawing>
              <GeometryDrawing.Geometry>
                  <RectangleGeometry Rect="0,0,1,1" />
              </GeometryDrawing.Geometry>
              <GeometryDrawing.Brush>
                  <LinearGradientBrush>
                       <GradientStop Color="Yellow" Offset="0" />
                       <GradientStop Color="Green" Offset="0.5" />
                       <GradientStop Color="Blue" Offset="1" />
                   </LinearGradientBrush>
              </GeometryDrawing.Brush>
           </GeometryDrawing>
        </DrawingBrush.Drawing>
     </DrawingBrush>