计算机图形学(三):Point3D,Color3D类的定义和使用
程序员文章站
2024-03-16 17:45:22
...
首先我们定义Point3D类,包含xyz字段,属性,各构造函数。定义Color3D类,包含xyz字段,属性,各构造函数。
Point3D类的属性和构造函数:
double _x;
double _y;
double _z;
public double X { get => _x; set => _x = value; }
public double Y { get => _y; set => _y = value; }
public double Z { get => _z; set => _z = value; }
public Point3D()
{
_x = 0;
_y = 0;
_z = 0;
}
public Point3D(double x, double y, double z)
{
_x = x;
_y = y;
_z = z;
}
Color3D类的属性和构造函数:
double _r;
double _g;
double _b;
public double R { get => _r; set => _r = value; }
public double G { get => _g; set => _g = value; }
public double B { get => _b; set => _b = value; }
//构造函数
//构造函数一
public Color3D()
{
_r = 0.0;
_g = 0.0;
_b = 0.0;
}
//构造函数二
public Color3D(double r,double g,double b)
{
_r = r;
_g = g;
_b = b;
}
第二步:重写(override)Point3D, Color3D的toString()方法, 让该Point3D, Color3D对象能够显示成类似(1,2,3)这样的形式。然后编写代码测试写的toString方法是否正确。
Point3D的toString()方法:
测试Point3D的toString()方法:
Color3D的toString()方法:
测试Color3D的toString()方法:
第三步:利用运算符重载,实现Point3D,Color3D类的如下运算: 点 + 向量, 向量 + 点, 点 – 点。 标量 * 颜色, 颜色 * 标量, 颜色 + 颜色, 颜色 – 颜色。然后编写代码测试上述方法是否编写正确。
Point3D的运算符重载:
//运算符重载:点 + 向量
public static Point3D operator +(Point3D a,Vector3D b)
{
return new Point3D(a.X + b.I, a.Y + b.J, a.Z + b.K);
}
//运算符重载:向量 + 点
public static Point3D operator +(Vector3D b, Point3D a)
{
return new Point3D(a.X + b.I, a.Y + b.J, a.Z + b.K);
}
//运算符重载:点 – 点
public static Vector3D operator -(Point3D a,Point3D b)
{
return new Vector3D(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
}
测试Point3D的运算符重载:
//测试Point3D的运算符重载
Point3D point3 = point1 + vector;
Point3D point4 = vector + point1;
Vector3D vector2 = point2 - point1;
经调试结果正确
color3D的运算符重载:
//运算符重载:标量 * 颜色
public static Color3D operator *(double c,Color3D a)
{
return new Color3D(c * a.R, c * a.G, c * a.B);
}
//运算符重载:颜色 * 标量
public static Color3D operator *(Color3D a, double c)
{
return new Color3D(c * a.R, c * a.G, c * a.B);
}
//运算符重载:颜色 + 颜色
public static Color3D operator +(Color3D b, Color3D a)
{
return new Color3D(b.R+a.R, b.G + a.G, b.B + a.B);
}
//运算符重载:颜色 – 颜色
public static Color3D operator -(Color3D b, Color3D a)
{
return new Color3D(b.R - a.R, b.G - a.G, b.B - a.B);
}
测试color3D的运算符重载:
//测试color3D的运算符重载
Color3D color2 =5.0*color1;
Color3D color3 =color1*5.0;
Color3D color4 =color2+color3;
Color3D color5 =color4-color3;
第四步:实现Color3D类的ToSys255Color方法,该方法返回C#中自带的Color对象,实现Color3D到Color的转换。其中,注意,转换成Color的rgb分量必须在0~255之间,对超过255的情况要进行处理。然后代码测试上述方法是否编写正确。
实现Color3D类的ToSys255Color方法:
//实现Color3D类的ToSys255Color方法,该方法返回C#中自带的Color对象,实现Color3D到Color的转换。
public Color ToSys255Color()
{
int r = (int)(_r * 255);
int g =(int) (_g * 255);
int b = (int)(_b * 255);
if(r>255)
{
r = 255;
}
if(r<0)
{
r = 0;
}
if (g > 255)
{
g = 255;
}
if (g < 0)
{
g = 0;
}
if (b > 255)
{
b = 255;
}
if (b < 0)
{
b = 0;
}
return Color.FromArgb(r,g,b);
}
调试ToSys255Color方法:
以上是个人思考的过程,难免有不足,有什么问题希望小伙伴一起讨论**(。・`ω´・)**