2011-07-30 105 views
4

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

回答

15

不要在这里使用一个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; 
     } 
    } 
} 
0

使用Padding有什么问题?

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

这可以很容易地与SizeMode属性

pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; 
完成
相关问题