0

I would like to have better quality of images of ToolStripMenuItems, so that they do not look pixelated.

Source code 1

private void button2_Click(object sender, EventArgs e)
{
    ContextMenuStrip cms = new ContextMenuStrip();
    cms.Items.Add("Test", Properties.Resources.path1092);
    cms.Show(button2, Cursor.Position);
}

Screenshot

context menu screenshot

The image file

original image

Source code 2

Here I am using this method:

internal static Bitmap ResizeToFitBoundingBox(Image image, in Rectangle box)
{
    float maxHeight = box.Width;
    float maxWidth = box.Height;

    float x = Math.Min(maxWidth / image.Width,
        maxHeight / image.Height);

    float newW = (float)image.Width * x;
    float newH = (float)image.Height * x;

    var bmp = new Bitmap((int)Math.Round(maxWidth),
        (int)Math.Round(maxHeight));
    bmp.MakeTransparent(Color.Empty);
    using (Graphics gr = Graphics.FromImage(bmp))
    {
        gr.DrawImage(image, (bmp.Width - newW) / 2,
            (bmp.Height - newH) / 2, newW, newH);
    }

    return bmp;
}

The first method looks like this:

private void button2_Click(object sender, EventArgs e)
{
    ContextMenuStrip cms = new ContextMenuStrip();

    ToolStripMenuItem item = new ToolStripMenuItem("Test");

    cms.Items.Add(item);

    cms.ImageList = new ImageList();
    cms.ImageList.ColorDepth = ColorDepth.Depth32Bit;
    cms.ImageList.TransparentColor = Color.Empty;
    cms.ImageList.ImageSize = new Size(128, 128);
    cms.ImageList.Images.Add(ResizeToFitBoundingBox(Properties.Resources.path1092,
        new Rectangle(Point.Empty, new Size(128, 128))));

    item.ImageTransparentColor = Color.Empty;
    item.ImageIndex = 0;
    item.ImageTransparentColor = Color.Empty;

    cms.Show(button2, Cursor.Position);
}

Screenshot 2

Aspect ratio kept:

aspect ratio kept

The problem is the same.

silviubogan
  • 3,343
  • 3
  • 31
  • 57
  • You will need a high-quality resize, however usually, you would have images with the sizes you needed premade. – TheGeneral Mar 08 '19 at 11:40
  • If the image is already transparent, remove `bmp.MakeTransparent();`. Add `gr.SmoothingMode = SmoothingMode.AntiAlias`. Using an ImageList, you don't need a resize method. Problem is, the Menu Item height is less than 128 pixels, apparently. You can have better results if you draw the Image in a new Bitmap using the Menu height as reference. Or with an ImageList sized accordingly. – Jimi Mar 08 '19 at 12:14
  • That's a heavy resize, about x6 smaller. No magic is going to make that look good. Looks like it uses alpha-blended anti-aliasing, that's how you get holes. You need to go back to the painting program and resize there. – Hans Passant Mar 08 '19 at 13:40

0 Answers0