如何在调整大小时使图片框中的图像居中?

12

当我调整窗体大小时,如何使图片框中的图像居中? 我手头有一个在面板中的图片框,所以如果图像大于图片框,则可以在面板上获取滚动条。 但是,这在图片框大小模式为“居中图像”时不起作用,仅在“自动大小”模式下起作用。

3个回答

25

使用SizeMode属性可以轻松完成此操作

pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;

18

不要在这里使用PictureBox,Panel已经完全能够通过其BackgroundImage属性显示居中的图像。 所需的一切就是打开它的DoubleBuffered属性以抑制闪烁。 在您的项目中添加一个新类,并粘贴下面显示的代码。编译。 从工具箱的顶部拖放新控件到您的窗体上,替换面板。 使用属性窗口或代码将其BackgroundImage属性分配。

using System;
using System.Drawing;
using System.Windows.Forms;

internal class PicturePanel : Panel {
    public PicturePanel() {
        this.DoubleBuffered = true;
        this.AutoScroll = true;
        this.BackgroundImageLayout = ImageLayout.Center;
    }
    public override Image BackgroundImage {
        get { return base.BackgroundImage; }
        set { 
            base.BackgroundImage = value;
            if (value != null) this.AutoScrollMinSize = value.Size;
        }
    }
}

1

使用填充有什么问题吗?

void picturebox_Paint(object sender, PaintEventArgs e)
{
    int a = picturebox.Width - picturebox.Image.Width;
    int b = picturebox.Height - picturebox.Image.Height;
    Padding p = new System.Windows.Forms.Padding();
    p.Left = a / 2;
    p.Top = b / 2;
    picturebox.Padding = p;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接