父图像放大时设置子图像背景

时间:2013-10-09 09:41:37

标签: c# winforms image graphics

我有一个图像控件,其中所选的图像可以放大IN和OUT。

用户可以在运行时对图像进行一些控制。放置控件后,如果用户放大图像,则控件不会缩放,而是相对于它们在图像中的位置移动。因此控件的位置在图像上保持相同,只是图像将被缩放。

说完这一切之后,要求是导出完整的图像以及用户添加的控件。

我使用以下代码实现了此功能:

Bitmap bmpCopy = new Bitmap(picEditIsdDiagram.Image);

Graphics canvas = Graphics.FromImage(bmpCopy);
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
try
{
    foreach (Control MeasurementSymbol in picEditIsdDiagram.Controls)
    {
        if (MeasurementSymbol is DevExpress.XtraEditors.HScrollBar || MeasurementSymbol is DevExpress.XtraEditors.VScrollBar)
        {
            continue;
        }

        Bitmap bmpControl = new Bitmap(MeasurementSymbol.Width, MeasurementSymbol.Height);
        MeasurementSymbol.DrawToBitmap(bmpControl, new Rectangle(Point.Empty, bmpControl.Size));
        bmpControl.MakeTransparent(Color.Transparent);

        canvas.DrawImage(
                            bmpCopy,
                            new Rectangle(0, 0, bmpCopy.Width, bmpCopy.Height),
                            new Rectangle(0, 0, bmpCopy.Width, bmpCopy.Height),
                            GraphicsUnit.Pixel
                        );

        canvas.DrawImage(bmpControl, ((UcMeasurementSymbol)MeasurementSymbol).PointInImage);
        canvas.Save();
    }

    FolderBrowserDialog save = new FolderBrowserDialog();

    save.RootFolder = Environment.SpecialFolder.Desktop;

    if (save.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        int count = 1;

        string destinationPath = save.SelectedPath + "\\" + IsdDiagram.Isd.Name + " - " + IsdDiagram.Name + ".Jpeg";

        while (File.Exists(destinationPath))
        {
            destinationPath = save.SelectedPath + "\\" + IsdDiagram.Isd.Name + " - " + IsdDiagram.Name + " [" + count++.ToString() + "].Jpeg";
        }

        bmpCopy.Save(destinationPath, ImageFormat.Jpeg);
        SERVICE.NMessageBox.Show("Complete Diagram saved successfully in Jpeg format", "Image Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}
catch (Exception ex)
{
    SERVICE.NMessageBox.Show("Error exporting complete Diagram. Error :" + ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

现在,当我缩放图像,然后单击“导出图”按钮时出现问题。 缩放后,仅显示图像的特定区域。因此,控件的背景(在控件的可见区域之外)图像被更改,而不是根据图像。

我附上图片以进一步澄清:

缩放前的图像:

enter image description here

缩放后的图像:

enter image description here

因此,在上面的图像中,您可以看到控制图像的背景不符合预期。

即使在应用ZOOM之后,有人可以帮助我获得正确的背景吗?

1 个答案:

答案 0 :(得分:0)

    MeasurementSymbol.DrawToBitmap(bmpControl, new Rectangle(Point.Empty, bmpControl.Size));
    bmpControl.MakeTransparent(Color.Transparent);

要回答的难题是为什么这段代码会产生一个透明的图像。换句话说,顶部图像是奇怪的,底部图像是正常的。像bmpControl这样的控件不会使用Color.Transparent绘制自己。然后,我们再也看不出可能是什么样的控制。

您需要停止使用控件来存储这些图像。将它们存储在位图中。只有这样才能确保你不依赖于控件的善意来以你希望的方式画出自己。并确保传递给MakeTransparent的颜色实际上与位图的背景颜色相匹配。如果它已经是透明的,使用支持PNG等透明度的图像格式,则根本不要调用MakeTransparent()。

相关问题