C++GDI+如何绘制带边框半径的矩形
这就是我使用GDI+绘制矩形的方式。
Graphics g(hdc);
SolidBrush blueColor((Color(255, 74, 134, 232)));
g.FillRectangle(&blueColor, x, y, width, height);
DeleteObject(&blueColor);
现在我想添加一些border-radius
,如何才能做到这一点?
解决方案
您可以通过GraphicsPath::AddArc及相关接口实现该功能。
一些为我工作的代码:
void GetRoundRectPath(GraphicsPath *pPath, Rect r, int dia)
{
// diameter can't exceed width or height
if(dia > r.Width) dia = r.Width;
if(dia > r.Height) dia = r.Height;
// define a corner
Rect Corner(r.X, r.Y, dia, dia);
// begin path
pPath->Reset();
// top left
pPath->AddArc(Corner, 180, 90);
// tweak needed for radius of 10 (dia of 20)
if(dia == 20)
{
Corner.Width += 1;
Corner.Height += 1;
r.Width -=1; r.Height -= 1;
}
// top right
Corner.X += (r.Width - dia - 1);
pPath->AddArc(Corner, 270, 90);
// bottom right
Corner.Y += (r.Height - dia - 1);
pPath->AddArc(Corner, 0, 90);
// bottom left
Corner.X -= (r.Width - dia - 1);
pPath->AddArc(Corner, 90, 90);
// end path
pPath->CloseFigure();
}
void DrawRoundRect(Graphics* pGraphics, Rect r, Color color, int radius, int width)
{
int dia = 2*radius;
// set to pixel mode
int oldPageUnit = pGraphics->SetPageUnit(UnitPixel);
// define the pen
Pen pen(color, 1);
pen.SetAlignment(PenAlignmentCenter);
// get the corner path
GraphicsPath path;
// get path
GetRoundRectPath(&path, r, dia);
// draw the round rect
pGraphics->DrawPath(&pen, &path);
// if width > 1
for(int i=1; i<width; i++)
{
// left stroke
r.Inflate(-1, 0);
// get the path
GetRoundRectPath(&path, r, dia);
// draw the round rect
pGraphics->DrawPath(&pen, &path);
// up stroke
r.Inflate(0, -1);
// get the path
GetRoundRectPath(&path, r, dia);
// draw the round rect
pGraphics->DrawPath(&pen, &path);
}
// restore page unit
pGraphics->SetPageUnit((Unit)oldPageUnit);
}
更多引用:RoundRect,WINAPI Edit control with custom border
相关文章