带边距的背景图像

时间:2013-04-30 08:18:18

标签: c# bitmap background margin zedgraph

我正在制作音频频谱图,它基本上是一个位图。为了显示轴(图形)我正在使用ZedGraph,它基本上只是为了显示轴,如上所述。一种帮手控制。然后我在上面显示Bitmap。 当窗口是默认大小时,这种方法很有效 - 但是,当我最大化它时,我会松散比例(见下图)。使用锚定很难(不可能?)。

现在我想知道其他可以保持正确定位的方案。是否可以为Control设置BackgroundImage(在我的案例中为ZedGraphControl)并设置它的边距?如果没有,最好的选择是什么?

默认窗口大小(一切正常): enter image description here

最大化窗口(位图未填充ZedGraphControl): enter image description here

1 个答案:

答案 0 :(得分:1)

在我看来,有两种解决方案。第一个是自己将波形位图绘制到控件上(因此使用完整的可用空间,但有点拉伸您的位图)。第二个是在控件周围构建一些面板并相应地调整它们的大小(使图形始终以正确的宽高比显示,但浪费屏幕空间并且更复杂)。

1 我不知道zedgraph是如何工作的,但是我提供了以下内容。 根据您的编写,它是一个用户控件。我要做的是听它的onPaint方法。 您将获得一个图形对象,您可以自由地在控件上绘制任何内容(包括位图)。参考控件的大小,您可以使用相应的宽高比轻松绘制位图。

<强> 2 创建一个容器来保存图形控件并添加四个面板,一个用于顶部,底部,左侧和右侧。就像这张图片一样:

您现在可以根据所需的宽高比调整这些大小。为此,您必须侦听两个事件,ResizeEnd事件(每当用户完成控件的大小调用时调用)和一个事件,以监听窗体是否已最大化(example)。 需要执行的代码如下:

        private void AdjustPanels(object sender, EventArgs e)
        {
        double desiredAspectRatio = 1;

        // I am using the form itself as a reference to the size and aspect ration of the application.
        // you can, of course, use any other control instead (e.g. a panel where you stuff all the other panels
        int width = this.Width;
        int height = this.Height;
        double formAspectRatio = (double)width / (double)height;

        int marginLeft=0, marginRight=0, marginTop=0, marginBottom=0;

        if (desiredAspectRatio > formAspectRatio)
        {
            // high aspect ratios mean a wider picture -> the picture we want is wider than what it currently is
            // so we will need a margin on top and bottom
            marginLeft = 0; marginRight = 0;
            marginTop = (int)((height - desiredAspectRatio * width) / 2);
            marginBottom = (int)((height - desiredAspectRatio * width) / 2);
        }
        else
        {
            marginTop = 0; marginBottom = 0;
            marginLeft = (int)((width - desiredAspectRatio*height)/2);
            marginRight = (int)((width - desiredAspectRatio * height) / 2);
        }

        pnlTop.Height = marginTop;
        pnlBottom.Height = marginBottom;
        pnlLeft.Width = marginLeft;
        pnlRight.Width = marginRight;
    }

当然,您必须将“desiredAspectRation”的值替换为波形图像的宽高比。 如果您需要进一步的帮助,只需发送一封包含您电子邮件地址的私人消息,我就会向您发送完整的Visual Studio解决方案。