I need to fill an rectangle on bottom of my image, but not over the image, so it should be a kind of append a rectangle to bottom of image.

What I have for now:

    private void DrawRectangle()
    {
        string imageFilePath = @"c:\Test.jpg";
        Bitmap bitmap = (Bitmap)Image.FromFile(imageFilePath);
        using (Graphics graphics = Graphics.FromImage(bitmap))
        {
            using (Image img = Image.FromFile(imageFilePath))
            {
                SolidBrush brush = new SolidBrush(Color.Black);
                int width = img.Width;
                int height = img.Height - 350;
                graphics.FillRectangle(brush, 0, height, width, 350);
            }
        }
        bitmap.Save(@"c:\Test1.jpg");
    }

But this is over the image.

Any idea's?

Thank you.

有帮助吗?

解决方案

You need to know the dimensions of your original image in order to set the size of the new bitmap, which must be larger to accommodate the rectangle.

private void DrawRectangle()
{
    string imageFilePath = @"c:\Test.jpg";
    int rectHeight = 100;

    using (Image img = Image.FromFile(imageFilePath)) // load original image
    using (Bitmap bitmap = new Bitmap(img.Width, img.Height + rectHeight)) // create blank bitmap of desired size
    using (Graphics graphics = Graphics.FromImage(bitmap))
    {
        // draw existing image onto new blank bitmap
        graphics.DrawImage(img, 0, 0, img.Width, img.Height); 
        SolidBrush brush = new SolidBrush(Color.Black);
        // draw your rectangle below the original image
        graphics.FillRectangle(brush, 0, img.Height, img.Width, rectHeight); 
        bitmap.Save(@"c:\Test1.bmp");
    }
}

其他提示

take a look at the FillRectangle() method overloads.. it has one with the following definition: FillRectangle(Brush brush, int PositionX, int PositionY, int Width, int Height)

your problem most likely stems on using an improper overload for what you're doing.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top