【发布时间】:2018-06-29 06:43:03
【问题描述】:
所以我一直在寻找这个问题很多,但结果总是回到将BackgroundImageLayout 设置为“拉伸”。当然,这对于保持原始图像的纵横比或关于如何在保持纵横比的同时手动缩放PictureBox 或其他加载的图像的教程没有做任何任何操作,但我无法(让我非常惊讶)找到任何关于如何让 WinForm 管理始终以窗口为中心的背景图像,拉伸以覆盖它,但保持与原始图像相同的纵横比。
我试过了:
public class CustomForm : Form
{
protected Size _scale;
protected Size _originalSize;
protected float _aspectRatio;
public CustomForm() : base()
{
this.DoubleBuffered = true;
}
private float AspectRatio() { return this.AspectRatio(this._originalSize); }
private float AspectRatio(int width, int height) { return (float)width / height; }
private float AspectRatio(Size value) { return this.AspectRatio(value.Width, value.Height); }
protected override void OnBackgroundImageChanged(EventArgs e)
{
this._originalSize = new Size(this.BackgroundImage.Width, this.BackgroundImage.Height);
this._aspectRatio = this.AspectRatio(this._originalSize);
base.OnBackgroundImageChanged(e);
}
protected override void OnPaintBackground(PaintEventArgs e)
{
if (this.BackgroundImage == null) base.OnPaintBackground(e);
else
{
e.Graphics.FillRectangle(new SolidBrush(this.BackColor), ClientRectangle);
int x = (this._scale.Width > this.Width) ? (int)Math.Round((this._scale.Width - this.Width) / 2.0) : 0;
int y = (this._scale.Height > this.Height) ? (int)Math.Round((this._scale.Height - this.Height) / 2.0) : 0;
e.Graphics.DrawImage(this.BackgroundImage, new Rectangle(x, y, this._scale.Width, this._scale.Height));
}
}
protected override void OnSizeChanged(EventArgs e)
{
if ( this._aspectRatio > this.AspectRatio(this.Size))
{
this._scale.Width = this.Width;
this._scale.Height = (int)(this.Width / this._aspectRatio);
}
else
{
this._scale.Height = this.Height;
this._scale.Width = (int)(this.Height * this._aspectRatio);
}
base.OnSizeChanged(e);
}
}
但它所做的只是将表单左上角的图像固定为其基本尺寸,而不管表单如何(重新)调整大小......
有人可以为我指出一个正确解决方案的方向,或者我到目前为止做错了什么吗?
谢谢!
【问题讨论】:
标签: c# winforms image-processing