ImageLayout.Center不会居中背景图像

时间:2015-07-10 11:17:36

标签: c# winforms

我想将背景图像居中。但是背景图像比我的控件(这是一个平面样式复选框)大。

A picture to make my problem clear enter image description here

通常如果背景图像小于控件,它将显示为黑盒子(正确居中);但在我的情况下,它将在绿色框(左上角)显示部分图像,但我想要的最终结果是橙色框(图像的中心),或按比例缩放以填充控件与额外部分切断( ImageLayout.Zoom将显示带有空格的整个图像。

更新:使用的代码:

        Image img = Image.FromFile("xxxx.png");
        mycheckbox.BackgroundImage = img;
        mycheckbox.BackgroundImageLayout = ImageLayout.Center;

1 个答案:

答案 0 :(得分:0)

可以使用

Image代替BackgroundImage将图像的一部分作为示例的橙色矩形。

如果图像没有填满整个复选框,并且可以接受更改正在设置的图像(应该没有问题,但在运行时复选框大小更改时不会动态),可以先调整图像大小根据最大的比例:

        var img = Image.FromFile("xxxx.png");
        float ratio = Math.Max(mycheckbox.Height / (float)img.Height,mycheckbox.Width / (float)img.Width);            
        if (ratio > 1)
        {
            Func<float, int> calc = f => (int)Math.Ceiling(f * ratio);
            var bmp = new Bitmap(img,  calc(img.Width ), calc(img.Height ));
            img.Dispose();
            img = bmp;
        }
        mycheckbox.ImageAlign = ContentAlignment.MiddleCenter;
        mycheckbox.Image = img;

线float ratio = Math.Max(mycheckbox.Height / (float)img.Height,mycheckbox.Width / (float)img.Width);只是计算高度比和宽度比。如果其中一个大于1,则表示复选框高度或宽度较大。哪个更大,哪个更大,因此Math.Max无关紧要。大于1的检查是以最大比率进行的,如果需要,图像以所述比率放大。

编辑 一种更通用的方法,可以缩放和剪切图像,以便在填充控件大小时可以使用BackGroundImage属性:

    public static void SetImage(this Control ctrl, Image img)
    {
        var cs = ctrl.Size;
        if (img.Size != cs)
        {
            float ratio = Math.Max(cs.Height / (float)img.Height, cs.Width / (float)img.Width);
            if (ratio > 1)
            {
                Func<float, int> calc = f => (int)Math.Ceiling(f * ratio);
                img = new Bitmap(img, calc(img.Width), calc(img.Height));                    
            }

            var part = new Bitmap(cs.Width, cs.Height);
            using (var g = Graphics.FromImage(part))
            {
                g.DrawImageUnscaled(img, (cs.Width - img.Width) /2, (cs.Height - img.Height) / 2);
            }                
            img = part;
        }
        ctrl.BackgroundImageLayout = ImageLayout.Center;
        ctrl.BackgroundImage = img;
    }