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

时间:2011-07-30 11:25:18

标签: c# image picturebox

在调整表单大小时,如何将图像置于图片框中心?我所拥有的是一个面板中的图片框,所以如果图像大于图片框,我可以在面板上获得滚动条。但这不适用于图片框大小模式“中心图像”,仅适用于“自动尺寸”。

3 个答案:

答案 0 :(得分:17)

不要在这里使用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 :(得分:5)

使用SizeMode属性

可以轻松完成
pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;

答案 2 :(得分:0)

使用填充有什么问题?

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;
}
相关问题