0

This is how I draw a rectangle using GDI+.

Graphics g(hdc);

SolidBrush blueColor((Color(255, 74, 134, 232)));                   
g.FillRectangle(&blueColor, x, y, width, height);
DeleteObject(&blueColor); 

Now I want to add some border-radius, how can I do that?

  • 1
    [How to draw a rounded rectangle in c#](https://stackoverflow.com/questions/33853434/how-to-draw-a-rounded-rectangle-in-c-sharp). It's c#, but you'll get the gist of it – Andy Apr 12 '21 at 04:48

1 Answers1

0

You can implement this function through GraphicsPath::AddArc and related APIs.

Some code that worked for me:

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);
}

More references: RoundRect, WINAPI Edit control with custom border

Zeus
  • 3,703
  • 3
  • 7
  • 20
  • Hi, does the answer solve your issue? Please feel free to let me know if you have any issue and also accept it if it does help. – Zeus May 04 '21 at 06:50