方向を計算し (必要に応じてベクトルと呼ぶこともできますが、実際には勾配です...)、y 値を指定して関数から x 値を取得したいと考えています。
基本的に、x、y 値から x、y 値に線を引こうとしていますが、方向があります。
たとえば、勾配/方向が 1/4 (Rise over Run)、始点が 200、終点の y 値が 250 の場合、x はどのように求められるでしょうか?
これが本当に基本的な高校の代数であることは知っていますが、何らかの理由でそれを概念化することはできません...
方向を計算し (必要に応じてベクトルと呼ぶこともできますが、実際には勾配です...)、y 値を指定して関数から x 値を取得したいと考えています。
基本的に、x、y 値から x、y 値に線を引こうとしていますが、方向があります。
たとえば、勾配/方向が 1/4 (Rise over Run)、始点が 200、終点の y 値が 250 の場合、x はどのように求められるでしょうか?
これが本当に基本的な高校の代数であることは知っていますが、何らかの理由でそれを概念化することはできません...
終点が A(x1,y1) と B(x2,y2) の場合、勾配は次のように定義されます。
m = ( y2 - y1 ) / ( x2 - x1 )
傾きがあるので、残りの座標を計算できるようにするには、少なくとも 3 つの座標が必要です。
あなたの質問から、y2を計算したいと思います。したがって、x1、y1、および x2 が必要です。
例:
m = 1/4
A(1,1)
B(9,y2)
---
y2 = ?
m = ( y2 - y1 ) / ( x2 - x1 )
y2 - y1 = m * ( x2 - x1 )
y2 = m * ( x2 - x1 ) + y1
y2 = 1/4 * ( 9 - 1 ) + 1
y2 = 3
そして、ここに多数の言語(javascriptを含む) での実装があります
点(x1,y1)と勾配mが与えられると、線上の他の点は次のように与えられます。
y = y1 + m*(x-x1) // point is (x,y)
Bresenham の直線アルゴリズム:
void DrawLineLCD(int x1,int y1,int x2,int y2,int nState)
{
unsigned int nTmp;
unsigned int nAlt=0;
int x,y; // where is the current pixel.
int dx; // dx is the delta for x
int dy; // dy is the delta for y
int StepVal=0; // variable for figuring out when to increment the other
axis.
if (x1>x2 && y1>y2)
{
nTmp=x2;
x2=x1;
x1=nTmp;
nTmp=y2;
y2=y1;
y1=nTmp;
dx=x2-x1; // dx is the delta for x
dy=y2-y1; // dy is the delta for y
}else
{
dx=x2-x1; // dx is the delta for x
dy=y2-y1; // dy is the delta for y
if (dy<0)
{
dy=-dy;
nTmp=y2;
y2=y1;
y1=nTmp;
nAlt=1;
}else
if (dx<0)
{
dx=-dx;
nTmp=x2;
x2=x1;
x1=nTmp;
nAlt=1;
}
}
if (nAlt)
{
if(dx>=dy) // The slope is less than 45 degres
{
y=y2;
for(x=x1; x<=x2; x++)
{
// Call your function to draw a pixel here.
SetPixelLCD(x,y,nState);
StepVal+=dy;
if(StepVal>=dx) // Increment y if enough x steps
// have been taken.
{
y--;
StepVal-=dx; // Reset StepVal, but
// not to 0. This gives even slopes.
}
}
}
else // The slope is greater than 45 degrees, just like
// above, but with y instead of x.
{
x=x2;
for(y=y1; y<=y2; y++)
{
// Call your function to draw a pixel here.
SetPixelLCD(x,y,nState);
StepVal+=dx;
if(StepVal>=dy)
{
x--;
StepVal-=dy;
}
}
}
return;
}
if(dx>=dy) // The slope is less than 45 degres
{
y=y1;
for(x=x1; x<=x2; x++)
{
// Call your function to draw a pixel here.
SetPixelLCD(x,y,nState);
StepVal+=dy;
if(StepVal>=dx) // Increment y if enough x steps
// have been taken.
{
y++;
StepVal-=dx; // Reset StepVal, but
// not to 0. This gives even slopes.
}
}
}
else // The slope is greater than 45 degrees, just like
// above, but with y instead of x.
{
x=x1;
for(y=y1; y<=y2; y++)
{
// Call your function to draw a pixel here.
SetPixelLCD(x,y,nState);
StepVal+=dx;
if(StepVal>=dy)
{
x++;
StepVal-=dy;
}
}
}
return;
}