首页 > 解决方案 > 如何设置 ContextMenuStrip 图像平滑模式?

问题描述

我希望ToolStripMenuItems 的图像质量更好,这样它们看起来就不会像素化。

源代码 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);
}

截屏

上下文菜单屏幕截图

图像文件

原始图像

源代码 2

这里我使用这种方法:

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

第一种方法如下所示:

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

截图 2

长宽比保持:

长宽比保持

问题是一样的。

标签: c#winformscontextmenustrip.net-4.6.1

解决方案


推荐阅读