简体   繁体   English

缩放和拉伸之间的backgroundimagelayout混合

[英]backgroundimagelayout hybrid between zoom and stretch

I am using Windows Forms and I'd like to place a background image in the upper left corner of my panel. 我正在使用Windows窗体,我想在面板的左上角放置一个背景图像。 I'd like to have the original height:width-ratio of the image preserved and the image should fill the control as much as possible. 我想保留图像的原始height:width-ratio ,并且图像应尽可能填充控件。

ImageLayout.Zoom centers the image, which I don't like, but preserves the ratio which is good. ImageLayout.Zoom使图像居中,这是我不喜欢的,但是保留了很好的比例。 ImageLayout.Stretch puts the image in the upper left corner (in all other corners) as desired, but does not preserve the ratio. ImageLayout.Stretch将图像按需要放置在左上角(所有其他角),但不保留比率。

So far I've used the approach of placing a picturebox into my panel that is resized based on its parent's size, when the parent is resized. 到目前为止,我已经使用了将图片框放置到面板中的方法,该图片框在调整父元素的大小时会根据其父元素的大小进行调整。 I can achieve the desired effect, but I feel that there must be a nicer and built-in way. 我可以达到预期的效果,但是我觉得必须有一种更好的内置方法。

try this: 尝试这个:

public class CustomPanel : Panel
{
    int x, y;
    public CustomPanel()
    {
        DoubleBuffered = true;
    }
    float scale;
    protected override void OnBackgroundImageChanged(EventArgs e)
    {
        scale = (float)BackgroundImage.Width / BackgroundImage.Height;
        base.OnBackgroundImageChanged(e);
    }
    protected override void OnPaintBackground(PaintEventArgs e)
    {
        if(BackgroundImage == null) base.OnPaintBackground(e);                        
        else {
         e.Graphics.FillRectangle(new SolidBrush(BackColor), ClientRectangle);
         e.Graphics.DrawImage(BackgroundImage, new Rectangle(0, 0, x,y));
        }
    }
    protected override void OnSizeChanged(EventArgs e)
    {
        if (scale > (float)Width / Height)
        {
            x = Width;
            y = (int)(Width / scale);
        }
        else
        {
            y = Height;
            x = (int)(Height * scale);
        }
        base.OnSizeChanged(e);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM