使用C#GDI+绘制多重黄金矩形
程序员文章站
2024-01-24 15:53:28
...
前段时间翻译的文章《(翻译)布局和矩形中的应用黄金分割比率》中介绍了如何绘制黄金矩形,并给出了1到5重黄金分割矩形的绘制图形,如下图所示。于是想在C#中用GDI+程序绘制黄金矩形。
从左往右看上述黄金矩形,从中发现绘制规律。首先看到绘制的矩形的大小,按数列排列的话为1、1、2、3、5,可以看到这符合 斐波那契数列的排列,也就是下一重矩形的边长为前两重矩形边长之和。
再看绘制矩形时的左上角坐标,从上图可以看出,从第二个图到第五个图是一个循环:以左边第一个图为基准,先右边画一个矩形,再在整个图形下方画一个矩形,再在整个图形左侧画一个矩形,再在整个图形上方画一个图。后续就是重复这个循环了。
主要的绘图代码如下:
//pGoldenRect为绘图控件
//记录待绘制的下个图矩形的左上角坐标
m_startX = pGoldenRect.Width / 2;
m_startY = pGoldenRect.Height / 2;
//保留整个图形的左上角坐标及高宽
int originX = 0;
int originY = 0;
int totalHeight = 0;
int totalWidth = 0;
//计算斐波那契数列
int n1 = 1;
int n2 = 1;
int n3 = 0;
//记录上上轮、上轮和本轮的
int n1Length = baseUnit;
int n2Length = baseUnit;
int n3Length = baseUnit;
GraphicsPath gp = new GraphicsPath();
gp.AddRectangle(new Rectangle(m_startX, m_startY, n1Length, n1Length));
originX = m_startX;
originY = m_startY;
totalHeight = n1Length;
totalWidth = n1Length;
m_startX = m_startX + n1Length;
gp.AddRectangle(new Rectangle(m_startX, m_startY, n2Length, n2Length));
totalWidth = n1Length + n2Length;
for (int i = 2; i < drawLoop; i++)
{
n3 = n1 + n2;
switch (i%4)
{
case 1:
m_startX = m_startX + n2Length;
n3Length = n3 * baseUnit;
totalWidth += n3Length;
break;
case 2:
m_startX = m_startX - n1Length;
m_startY += n2Length;
n3Length = n3 * baseUnit;
totalWidth = n3Length;
totalHeight += n3Length;
break;
case 3:
m_startY -= n1Length;
n3Length = n3 * baseUnit;
m_startX = m_startX - n3Length;
originX = m_startX;
originY = m_startY;
totalWidth = n3Length + n2Length;
totalHeight = n3Length;
break;
case 0:
n3Length = n3 * baseUnit;
m_startY -= n3Length;
originY = m_startY;
totalHeight += n3Length;
break;
}
gp.AddRectangle(new Rectangle(m_startX, m_startY, n3Length, n3Length));
n1 = n2;
n2 = n3;
n1Length = n2Length;
n2Length = n3Length;
}
g.DrawPath(new Pen(m_goldenColor, 1), gp);
程序执行效果如下:
能绘制单个的黄金矩形,就可以接着绘制水平黄金矩形网格和垂直黄金矩形网格,各位朋友可以试试。
参考文献:
[1]https://uxmovement.com/content/applying-the-golden-ratio-to-layouts-and-rectangles/
[2]https://baike.baidu.com/item/%E6%96%90%E6%B3%A2%E9%82%A3%E5%A5%91%E6%95%B0%E5%88%97