An extension method for WPF 3D Models

Source: Internet
Author: User

In WPF 3D, we often need to change the color of a ModelVisual3D object.

Let's first talk about ModelVisual3D. In essence, 3D models are made up of triangles and are rendered by materials (DiffuseMaterial ).

 

This is a ModelVisual3D xaml code:

<ModelVisual3D x: Name = "d18">
<ModelVisual3D. Content>
<GeometryModel3D x: Name = "DefaultMaterial" d: Bounds = "-156.412704467773,-34.2943992614746,-13.5738000869751, 84.2265014648438, 42.2536993026733, 27.1476001739502">
<GeometryModel3D. Geometry>
<MeshGeometry3D Normals = "0,-0,-0,-0,-,-, 0, 0, 0, 0 0 0,-1, -1 0, 0,-1 0,-1 0,-1 0,-1
0, 0, 1 0,... "/>
</GeometryModel3D. Geometry>
<GeometryModel3D. Material>
<DiffuseMaterial Brush = "White"/>
</GeometryModel3D. Material>
</GeometryModel3D>
</ModelVisual3D. Content>

 

The hierarchical structure is ModelVisual3D-> ModelVisual3D. Content-> GeometryModel3D-> GeometryModel3D. Material

The Gemetry of GeometryModel3D defines all coordinates, and connects these coordinates to the skeleton of the Model Block. Material defines the skin of the skeleton.

For more explanations, go to msdn. I have written a general method to modify the color of the model:

 

Public static class RenderExtension
{
Public static void SetColor (this ModelVisual3D visual3D, Brush color)
{
GeometryModel3D geometrymodel = visual3D. Content as GeometryModel3D;

If (geometrymodel. Material is MaterialGroup)
{
Var materialGroup = geometrymodel. Material as MaterialGroup;
Foreach (var groupItem in materialGroup. Children)
{
If (groupItem is DiffuseMaterial)
{
DiffuseMaterial tmpItem = groupItem as DiffuseMaterial;
TmpItem. Brush = color;
}
}
}
Else
{
DiffuseMaterial material = geometrymodel. Material as DiffuseMaterial;
If (material! = Null)
{
Material. Brush = color;
}
}
}

}

 

 

You only need to write: visual3D. SetColor (Brushes. Red );

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.