嘗試了多個(gè)版本雏逾,最好用的還是正點(diǎn)原子LCD驅(qū)動(dòng)提供的版本。
-
x軸掃描法
沒有進(jìn)行任何優(yōu)化郑临,掃描也是最簡(jiǎn)單的沿著x軸掃描栖博,y軸以斜率k逼近,最后采用四舍五入完成繪圖厢洞。
特點(diǎn)是只能畫斜率比較小的線仇让,斜率增大后會(huì)出現(xiàn)明顯的鋸齒,垂直直線畫出來就只剩下散點(diǎn)躺翻。
優(yōu)點(diǎn)也有丧叽,就是易于理解,畫圖速度高公你。
void LCD_DrawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, unsigned int color)
{
if (x1 < x0)
{
int t = x0;
x0 = x1;
x1 = t;
t = y0;
y0 = y1;
y1 = t;
}
int x;
float dx, dy, y, k;
dx = x1 - x0;
dy = y1 - y0;
k = dy / (float)dx;
y = y0;
// int step = x1>x0? 1 : -1;
for (x = x0; x <= x1; x++)
{
LCD_DrawPixel(x, (int)(y + 0.5), color);
y = y + k;
}
}
-
正點(diǎn)原子優(yōu)化方法
采用了自適應(yīng)逼近方法踊淳,自動(dòng)選取最合適的增量方式,并規(guī)避了浮點(diǎn)數(shù)運(yùn)算陕靠。
void LCD_DrawLine(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2, unsigned int color)
{
uint16_t t;
int xerr = 0, yerr = 0, delta_x, delta_y, distance;
int incx, incy, uRow, uCol;
delta_x = x2 - x1; //計(jì)算坐標(biāo)增量
delta_y = y2 - y1;
uRow = x1;
uCol = y1;
if (delta_x > 0)
incx = 1; //設(shè)置單步方向
else if (delta_x == 0)
incx = 0; //垂直線
else
{
incx = -1;
delta_x = -delta_x;
}
if (delta_y > 0)
incy = 1;
else if (delta_y == 0)
incy = 0; //水平線
else
{
incy = -1;
delta_y = -delta_y;
}
if (delta_x > delta_y)
distance = delta_x; //選取基本增量坐標(biāo)軸
else
distance = delta_y;
for (t = 0; t <= distance + 1; t++) //畫線輸出
{
LCD_DrawPixel(uRow, uCol, color); //畫點(diǎn)
xerr += delta_x;
yerr += delta_y;
if (xerr > distance)
{
xerr -= distance;
uRow += incx;
}
if (yerr > distance)
{
yerr -= distance;
uCol += incy;
}
}
}