画渐变⾊的C++代码
利⽤API GradientFill画矩形渐变⾊,可以采⽤多种颜⾊。
代码如下:
#include <wingdi.h>
//把$(BCB)LibPsdkmsimg32.lib加⼊到⼯程中
/*
函数名: DrawGraden渐变颜代码大全
功  能: 画矩形渐变⾊, 可以使⽤多种颜⾊
参  数: hdc - 上下⽂句柄
Rect - 整个画渐变的矩形范围
cl - 颜⾊数组
Num - 颜⾊数组中元素个数
dwMode - 模式, 可以使⽤GRADIENT_FILL_RECT_H 和 GRADIENT_FILL_RECT_V
返回值: 成功返回TRUE, 失败返回FALSE, GetLastError 错误信息获取;
*/
BOOL __fastcall DrawGraden(HDC hdc, CONST RECT *pRect, CONST DWORD *cl, int Num, DWORD dwMode)
{
int Width;
int Height;
TRIVERTEX *pvert;
GRADIENT_RECT    *pgRect;
if (cl == NULL || Num < 1 || pRect == NULL || dwMode == GRADIENT_FILL_TRIANGLE)
{
::SetLastError(ERROR_INVALID_PARAMETER);
return TRUE;
}
if (Num == 1)
{
HBRUSH hBrush = CreateSolidBrush(cl[0]);
SelectObject(hdc, hBrush);
FillRect(hdc, pRect, hBrush);
DeleteObject(hBrush);
return TRUE;
}
pvert = new TRIVERTEX[Num * 2 - 2];
pgRect = new GRADIENT_RECT[Num];
Width = pRect->right - pRect->left;
Height = pRect->bottom - pRect->top;
for (int i = 0; i < Num - 1; i++)
{
if (dwMode == GRADIENT_FILL_RECT_V)
{
pvert[i * 2].x = pRect->left;
pvert[i * 2].y = pRect->top + Height / (Num - 1) * i;
pvert[i * 2 + 1].x = pRect->right;
pvert[i * 2 + 1].y = pRect->top + Height / (Num - 1) * (i + 1);
}
else if (dwMode == GRADIENT_FILL_RECT_H)
{
pvert[i * 2].x = pRect->left + Width / (Num - 1) * i;
pvert[i * 2].y = pRect->top;
pvert[i * 2 + 1].x = pRect->left + Width / (Num - 1) * (i + 1);
pvert[i * 2 + 1].y = pRect->bottom;
}
pvert[i * 2] .Red    = (WORD)GetRValue((cl[i])) << 8;
pvert[i * 2] .Green  = (WORD)GetGValue((cl[i])) << 8;
pvert[i * 2] .Blue  = (WORD)GetBValue((cl[i])) << 8;
pvert[i * 2] .Alpha  = 0x0000;
pvert[i * 2 + 1] .Red    = (WORD)GetRValue((cl[i + 1])) << 8;
pvert[i * 2 + 1] .Green  = (WORD)GetGValue((cl[i + 1])) << 8;
pvert[i * 2 + 1] .Blue  = (WORD)GetBValue((cl[i + 1])) << 8;
pvert[i * 2 + 1] .Alpha  = 0x0000;
pgRect[i].UpperLeft  = i * 2;
pgRect[i].LowerRight = i * 2 + 1;
}
BOOL bRet = ::GradientFill(hdc, pvert, Num * 2, pgRect, Num - 1, dwMode);
delete []pvert;
delete []pgRect;
return bRet;
}
BCB应⽤代码和效果图:
void __fastcall TForm2::FormPaint(TObject *Sender)
{
DWORD cl[5] = {clGreen, clYellow, clRed, clBlue, clFuchsia};
DrawGraden(this->Canvas->Handle, &(this->ClientRect), cl, 5,  GRADIENT_FILL_RECT_H); }

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。