简体   繁体   English

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

[英]How to center image in picturebox on resize?

How can I center an image in a picturebox as I resize the form? 在调整表单大小时,如何将图像置于图片框中心? What I have is a picturebox in a panel so if the image is larger than the picturebox, I can get scrollbars on the panel. 我所拥有的是一个面板中的图片框,所以如果图像大于图片框,我可以在面板上获得滚动条。 But this doesn't work with the picturebox size mode "Center Image" and only works with "Auto Size". 但这不适用于图片框大小模式“中心图像”,仅适用于“自动尺寸”。

Don't use a PictureBox here, a Panel is already perfectly capable of displaying a centered image through its BackgroundImage property. 不要在这里使用PictureBox,Panel已经完全能够通过其BackgroundImage属性显示居中的图像。 All that's needed is to turn on its DoubleBuffered property to suppress flicker. 所需要的只是打开其DoubleBuffered属性以抑制闪烁。 Add a new class to your project and paste the code shown below. 在项目中添加一个新类并粘贴下面显示的代码。 Compile. 编译。 Drop the new control from the top of the toolbox onto your form, replacing the panel. 将新控件从工具箱顶部拖放到表单上,替换面板。 Assign its BackgroundImage property with the Properties window or in your code. 使用“属性”窗口或代码分配其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;
        }
    }
}

使用SizeMode属性可以轻松完成此操作

pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;

What's wrong with using Padding? 使用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;
}

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

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