如何在调整大小时使图片在图片框中居中?

问题描述 投票:0回答:3

如何在调整表单大小时将图片居中放置在图片框中?我所拥有的是面板中的图片框,因此如果图像大于图片框,我可以在面板上获得滚动条。但这不适用于图片框大小模式“中心图像”,仅适用于“自动调整大小”。

c# image picturebox
3个回答
22
投票

这可以通过 SizeMode 属性轻松完成

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

18
投票

这里不要使用 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;
        }
    }
}

1
投票

使用 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;
}
© www.soinside.com 2019 - 2024. All rights reserved.