C#中picturebox怎么完全显示图片?
C#中picturebox怎么完全显示图片?
这样不行!!!
openFileDialog1.Filter = "*.BMP,*.JPG;*.GIF|*.BMP;*.JPG;*.GIF";
openFileDialog1.ShowDialog();
Image a =Image.FromFile(openFileDialog1.FileName);
pictureBox1.Image = a;
pictureBox1.Height = a.Height;
pictureBox1.Width = a.Width;
------解决方案--------------------
完全显示图片的含义是什么?
以下代码将图像完整的显示在pictureBox里,图像比例会发生变化。
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "*.BMP,*.JPG;*.GIF|*.BMP;*.JPG;*.GIF";
openFileDialog1.ShowDialog();
Image a = Image.FromFile(openFileDialog1.FileName);
Bitmap bit = new Bitmap(pictureBox1.Width,pictureBox1.Height);
Graphics g = Graphics.FromImage(bit);
g.DrawImage(a, new Rectangle(0,0,bit.Width,bit.Height), new Rectangle(0,0,a.Width,a.Height), GraphicsUnit.Pixel);
pictureBox1.Image = bit;
------解决方案--------------------
如果只是原大小显示,你可能需要使用滚动条,PictureBox本身可能不会显示这个滚动条。不过你可以通过自己编写一个控件来达到这个要求可以参考下面的代码:
class ImgCtr : UserControl
{
private Image m_Image;
private float m_Scale;
public ImgCtr()
{
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true);
this.m_Scale = 1.0f;
}
public Image Image
{
get
{
return m_Image;
}
set
{
m_Image = value;
SizeF size = new SizeF(this.m_Image.Width * this.m_Scale, this.m_Image.Height * this.m_Scale);
this.AutoScrollMinSize = Size.Ceiling(size);
}
}
public void ScaleImage(float scale)
{
SizeF size = new SizeF(this.m_Image.Width * this.m_Scale, this.m_Image.Height * this.m_Scale);
this.AutoScrollMinSize = Size.Ceiling(size);
this.Invalidate();
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (this.CanFocus)
{
this.Focus();
}
base.OnMouseDown(e);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
PointF start = new PointF(this.AutoScrollPosition.X / this.m_Scale, this.AutoScrollPosition.Y / this.m_Scale);
this.drawImage(e.Graphics, start);
}
private void drawImage(Graphics g, PointF start)
{
g.ScaleTransform(this.m_Scale, this.m_Scale, MatrixOrder.Append);
g.DrawImage(this.m_Image, start.X, start.Y, this.m_Image.Width, this.m_Image.Height);
g.DrawRectangle(SystemPens.Desktop, start.X, start.Y, this.m_Image.Width - 1, this.m_Image.Height - 1);
}
}
------解决方案--------------------
唉,代码太长了,换一个吧:
C# code
public class ImageCtr : UserControl
{
private Image m_Img;
public Image Img
{
get { return m_Img; }
set
{
if (value != this.m_Img)
{
m_Img = value;
if (this.m_Img != null)
{
this.AutoScrollMinSize = this.m_Img.Size;
}
else
{
this.AutoScrollMinSize = Size.Empty;
}
this.Invalidate();
}
}
}
public ImageCtr()
{
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer, true);
}
protected override void OnPaint(PaintEventArgs e)
{