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

Jac*_*ack 7 c# image picturebox

在调整表单大小时,如何将图像置于图片框中心?我所拥有的是一个面板中的图片框,所以如果图像大于图片框,我可以在面板上获得滚动条.但这不适用于图片框大小模式"中心图像",仅适用于"自动尺寸".

Han*_*ant 17

不要在这里使用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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 8

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

pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
Run Code Online (Sandbox Code Playgroud)