- 您需要画线功能(在您的情况下为 g.drawline(x0,y0,x1,y1); )。
- 不关心颜色(你可以稍后再玩)
- 您需要定义您的图案(线条和空间的大小以像素为单位)
- 例如 int pattern[]={10,-5,0} (10px 行,然后 5px 空格,0 表示从头开始重复)... -值是空格 + 值是行
- 您需要“全局”状态(模式中的实际索引和绘制的实际像素长度),您也可以拥有全局模式指针或将所有内容封装在类/结构中。
好的,基本思想是将任何行分割为选定的模式,例如如下所示:
//---------------------------------------------------------------------------
// pattern draw state
int _pattern_ix=0; // actual index in pattern need to reset it to zero before any pattern change
double _pattern_l=0; // already drawed or skipped pixels from actual pattern[_pattern_ix]
// predefined patterns
int _pattern_dash_dash[]={ 10,-10, 0 };
int _pattern_dash_dot[] ={ 10,- 5, 1,- 5,0 };
int _pattern_dot_dot[] ={ 1,- 5, 0 };
//---------------------------------------------------------------------------
// draw line function
void drawline(int x0,int y0,int x1,int y1)
{
// this is just borland GDI access to draw line function
Form1->Canvas->MoveTo(x0,y0);
Form1->Canvas->LineTo(x1,y1);
}
//---------------------------------------------------------------------------
void pattern_line(int x0,int y0,int x1,int y1,int *pattern)
{
int p;
double x,y,xx,yy,dx,dy,dl,t,dt;
dx=x1-x0;
dy=y1-y0;
dl=sqrt((dx*dx)+(dy*dy));
dx/=dl; dy/=dl;
for (t=0.0,dt=0.0;dl>=0.5;)
{
p=pattern[_pattern_ix];
if (p<0) // skip
{
dt=-p-_pattern_l; // t=space to skip [px]
if (dt>dl) { _pattern_l+=dl; return; } // space is bigger then rest of line
dl-=dt; t+=dt; _pattern_l=0.0; // update line params and continue to next pattern entry
}
else // draw
{
dt=+p-_pattern_l; // t=space to draw [px]
x=x0+double(t*dx); // actual point pos
y=y0+double(t*dy); // space is bigger then rest of line
if (dt>dl) { _pattern_l+=dl; drawline(x,y,x1,y1); return; }
dl-=dt; t+=dt; _pattern_l=0.0; // update line params
xx=x0+double(t*dx); // actual point pos
yy=y0+double(t*dy);
drawline(x,y,xx,yy); // draw line and continue to next pattern entry
}
_pattern_ix++;
if (!pattern[_pattern_ix]) _pattern_ix=0;
}
}
//---------------------------------------------------------------------------
void main()
{
// borland GDI clear screen and color settings
Canvas->Brush->Color=clBlack;
Canvas->Pen->Color=clWhite;
Canvas->FillRect(ClientRect);
// draw dash-dot-ed rectangle
int x0,x1,y0,y1;
x0=30; x1=200;
y0=30; y1=100;
pattern_line(x0,y0,x1,y0,_pattern_dash_dot);
pattern_line(x1,y0,x1,y1,_pattern_dash_dot);
pattern_line(x1,y1,x0,y1,_pattern_dash_dot);
pattern_line(x0,y1,x0,y0,_pattern_dash_dot);
}
//---------------------------------------------------------------------------
并且不要忘记在任何图案样式更改之前将图案 ix,l 重置为零。
代码没有优化,所以它相当慢,但我希望足够简单理解。