上一节写了简单的立体绘制,相信大家也可以绘制很多种立体图形了。接下来要讲的是纹理贴图,说到纹理贴图,相信随便百度下就一大把,不过大多都是2D平面贴图。说到这肯定有人要说了,纹理贴图不就只支持平面2D吗?各位息怒,把刀先放下!且听我慢慢道来。
我记得我原来学习纹理的时候,百度一下到处都是,照着弄一下也很顺,可是出来就是个平面图片。我心想,我们要做的是3D啊,怎么一直教我在平面上搞,作为小白的我,那时候也是很郁闷的。郁闷久了反而想通了:我画立体图形的时候不也是一个面一个面的画吗?那我就一个面一个面的贴图不就好了?跟着这个想法,我开始了探索。
按照上一节的代码基础,我在界面加载时先加入一张图片:
Bitmap _bitmap = new Bitmap("D:\\Red墙.jpg");
BitmapData bitmapData = _bitmap.LockBits(
new Rectangle(0, 0, _bitmap.Width, _bitmap.Height),
ImageLockMode.ReadOnly,
System.Drawing.Imaging.PixelFormat.Format32bppArgb
);
然后绑定到纹理:
GL.GenTextures(1, out TextureID);
GL.BindTexture(TextureTarget.Texture2D, TextureID);
GL.TexImage2D(
TextureTarget.Texture2D,
0,
PixelInternalFormat.Rgba,
bitmapData.Width,
bitmapData.Height,
0,
OpenTK.Graphics.OpenGL.PixelFormat.Bgra,
PixelType.UnsignedByte,
bitmapData.Scan0
);
_bitmap.UnlockBits(bitmapData);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
接下来就是绘图部分了:
GL.Enable(EnableCap.Texture2D);
int sides = 40;
float radius = 1;
Vector3[] Points = new Vector3[sides + 1];
for (int i = 0; i < sides + 1; i++)
{
Points[i].X = radius * (float)Math.Cos(- Math.PI + i * 2 * Math.PI / sides);
Points[i].Y = radius * (float)Math.Sin(-Math.PI + i * 2 * Math.PI / sides);
Points[i].Z = 0;
}
GL.Begin(BeginMode.Quads);
for (int i = 0; i < sides; i++)
{
GL.TexCoord2((float)i / sides, 1);
GL.Vertex3(Points[i]);
GL.Normal3(Vector3d.Normalize(new Vector3d(Points[i].X, Points[i].Y, 0)));
GL.TexCoord2((float)i / sides, 0);
GL.Vertex3(Points[i] + new Vector3(0, 0, 3));
GL.Normal3(Vector3d.Normalize(new Vector3d(Points[i].X, Points[i].Y, 0)));
GL.TexCoord2((float)(i + 1) / sides, 0);
GL.Vertex3(Points[i + 1] + new Vector3(0, 0, 3));
GL.Normal3(Vector3d.Normalize(new Vector3d(Points[i + 1].X, Points[i + 1].Y, 0)));
GL.TexCoord2((float)(i + 1) / sides, 1);
GL.Vertex3(Points[i + 1]);
GL.Normal3(Vector3d.Normalize(new Vector3d(Points[i + 1].X, Points[i + 1].Y, 0)));
}
GL.End();
GL.Disable(EnableCap.Texture2D);
这边是绘制的一个圆柱侧面上的贴图,把侧面分成了无数块小长方形,然后按照比例把每一小块图片贴上。
效果:
结尾:不明白的童鞋可以举手啊,在下方评论,看到必回。另外,如果有大佬看到的话希望可以不吝赐教。