原文:
WPF 3D模型的一个扩展方法
<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,-1,0 0,-1,0 0,-1,0 0,-1,0 0,1,0 0,1,0 0,1,0 0,1,0 0,0,-1 0,0,-1 0,0,-1 0,0,-1 0,0,-1
0, 0, 1 0,... " />
</GeometryModel3D.Geometry>
<GeometryModel3D.Material>
<DiffuseMaterial Brush= " White "/>
</GeometryModel3D.Material>
</GeometryModel3D>
</ModelVisual3D.Content>
在WPF 3D中,我们常常需要改变一个ModelVisual3D对象的颜色。
先说说ModelVisual3D,本质上3D模型都是由一个个的三角形构成的,并且经过材质进行渲染(DiffuseMaterial) 。
这是一个ModelVisual3D的xaml代码:
<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,-1,0 0,-1,0 0,-1,0 0,-1,0 0,1,0 0,1,0 0,1,0 0,1,0 0,0,-1 0,0,-1 0,0,-1 0,0,-1 0,0,-1
0, 0, 1 0,... " />
</GeometryModel3D.Geometry>
<GeometryModel3D.Material>
<DiffuseMaterial Brush= " White "/>
</GeometryModel3D.Material>
</GeometryModel3D>
</ModelVisual3D.Content>
层级结构是ModelVisual3D->ModelVisual3D.Content->GeometryModel3D->GeometryModel3D.Material
其中GeometryModel3D的Gemetry就定义了所有的坐标,将这些坐标连起来就是这个模型块的骨骼;Material就定义了这个骨骼的皮肤。
更多的解释去看msdn吧,我这里写了个通用方法修改模型的颜色:
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;
}
}
}
{
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;
}
}
}
}
调用的时候只要写:visual3D.SetColor(Brushes.Red);就可以了