微分差值 透明颜色计算 使用C++ 的模板函数 去实现 结合EasyX做一个简单示例
我们先来看效果
那么,下面直接上代码,代码注释完成,是一个完整的控制台应用程序,使用VS可正常编译运行,前提是你有安装EasyX库
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#include<graphics.h>
template<typename T
,typename E
>
T
AlgoSmooth(T start
, T end
, E rate
)
{
return start
+ rate
*(end
-start
);
}
template<typename T
,typename E
>
T
AlgoTransparent(T front
, T behind
, E rate
)
{
return front
*rate
+ behind
*(1.0-rate
);
}
int getR(COLORREF c
)
{
return c
& 0xff;
}
int getG(COLORREF c
)
{
return (c
>>8) & 0xff;
}
int getB(COLORREF c
)
{
return (c
>>16) & 0xff;
}
double distance(int x1
,int y1
, int x2
, int y2
)
{
return sqrt(pow(x2
-x1
,2.0)+pow(y2
-y1
,2.0));
}
int main(int argc
, char * argv
[])
{
srand((unsigned int)time(NULL));
int winWid
= 720;
int winHei
= 480;
initgraph(winWid
, winHei
);
POINT ps
= {0,0};
POINT pe
= { winWid
, winHei
};
COLORREF cs
= 0x2255ff;
COLORREF ce
= 0xff6622;
COLORREF tr
= 0x00ff00;
COLORREF bl
= 0xff0000;
while (1)
{
int dx
= pe
.x
- ps
.x
;
dx
*= 2;
for (int i
= 0; i
< dx
; i
++)
{
double rate
= i
*1.0 / dx
;
int px
= AlgoSmooth(ps
.x
, pe
.x
, rate
);
int py
= AlgoSmooth(ps
.y
, pe
.y
, rate
);
int pr
= AlgoSmooth(getR(cs
), getR(ce
), rate
);
int pg
= AlgoSmooth(getG(cs
), getG(ce
), rate
);
int pb
= AlgoSmooth(getB(cs
), getB(ce
), rate
);
putpixel(px
, py
, RGB(pr
, pg
, pb
));
double maxDis
= distance(px
, py
, winWid
, 0);
for (int j
= py
-1; j
>=0; j
--)
{
double curDis
= distance(px
, j
, winWid
, 0);
double ra
= curDis
/ maxDis
;
int cr
= AlgoTransparent(pr
, getR(tr
), ra
);
int cg
= AlgoTransparent(pg
, getG(tr
), ra
);
int cb
= AlgoTransparent(pb
, getB(tr
), ra
);
putpixel(px
, j
, RGB(cr
, cg
, cb
));
}
maxDis
= distance(px
, py
, 0, winHei
);
for (int j
= py
+ 1; j
< winHei
; j
++)
{
double curDis
= distance(px
, j
, 0, winHei
);
double ra
= curDis
/ maxDis
;
int cr
= AlgoTransparent(pr
, getR(bl
), ra
);
int cg
= AlgoTransparent(pg
, getG(bl
), ra
);
int cb
= AlgoTransparent(pb
, getB(bl
), ra
);
putpixel(px
, j
, RGB(cr
, cg
, cb
));
}
}
cs
= ce
;
ce
= RGB(rand() % 255, rand() % 255, rand() % 255);
tr
= RGB(rand() % 255, rand() % 255, rand() % 255);
bl
= RGB(rand() % 255, rand() % 255, rand() % 255);
}
closegraph();
return 0;
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-33695.html