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

C# 如何在调整大小时将图片框中的图像居中?,c#,image,picturebox,C#,Image,Picturebox,如何在调整窗体大小时将图像居中放置在picturebox中?我在面板中有一个图片框,因此如果图像比图片框大,我可以在面板上获得滚动条。但这不适用于picturebox大小模式“中心图像”,仅适用于“自动大小” 此处不要使用PictureBox,面板已经完全能够通过其BackgroundImage属性显示居中图像。所需要的只是打开它的双缓冲属性来抑制闪烁。向项目中添加一个新类并粘贴如下所示的代码。编译。将新控件从工具箱顶部放到窗体上,替换面板。使用“属性”窗口或在代码中指定其BackgroundI

如何在调整窗体大小时将图像居中放置在picturebox中?我在面板中有一个图片框,因此如果图像比图片框大,我可以在面板上获得滚动条。但这不适用于picturebox大小模式“中心图像”,仅适用于“自动大小”

此处不要使用PictureBox,面板已经完全能够通过其BackgroundImage属性显示居中图像。所需要的只是打开它的双缓冲属性来抑制闪烁。向项目中添加一个新类并粘贴如下所示的代码。编译。将新控件从工具箱顶部放到窗体上,替换面板。使用“属性”窗口或在代码中指定其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;
        }
    }
}

使用填充物有什么问题

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

这可以通过SizeMode属性轻松完成

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