【问题标题】:How can I prevent the pasted image from overflowing its boundaries?如何防止粘贴的图像溢出其边界?
【发布时间】:2016-06-24 06:55:02
【问题描述】:

我将图像插入 Excel 范围,如下所示:

    private System.Drawing.Image _logo;

    public ProduceUsageRpt(..., System.Drawing.Image logo)
    {
        . . .
        _logo = logo;
    }
    . . .
    var logoRange = _xlSheet.Range[
    _xlSheet.Cells[LOGO_FIRST_ROW, _grandTotalsColumn], _xlSheet.Cells[LOGO_LAST_ROW, _grandTotalsColumn]];
Clipboard.SetDataObject(_logo, true);
_xlSheet.Paste(logoRange, _logo);

很遗憾,图片对于该范围来说太大了(目前是第 1 行到第 4 行第 16 列)。它没有做礼貌的事情并缩小自身以适应规定的范围,而是溢出并超出其指定的垂直和水平位置。

如何让图像按比例缩小并将其自身限制在“框”内?

【问题讨论】:

    标签: c# image scaling excel-interop image-scaling


    【解决方案1】:

    我在一个相关问题here 上改编了一个答案。

    只要我使范围足够大,就可以了:

        . . .
        var logoRange = _xlSheet.Range[
            _xlSheet.Cells[LOGO_FIRST_ROW, _grandTotalsColumn], _xlSheet.Cells[LOGO_LAST_ROW, _grandTotalsColumn+1]];
        PlacePicture(_logo, logoRange);
    }
    
    // From Jürgen Tschandl
    private void PlacePicture(Image picture, Range destination)
    {
        Worksheet ws = destination.Worksheet;
        Clipboard.SetImage(picture);
        ws.Paste(destination, false);
        Pictures p = ws.Pictures(System.Reflection.Missing.Value) as Pictures;
        Picture pic = p.Item(p.Count) as Picture;
        ScalePicture(pic, (double)destination.Width, (double)destination.Height);
    }
    
    // Also from Jürgen Tschandl
    private void ScalePicture(Picture pic, double width, double height)
    {
        double fX = width / pic.Width;
        double fY = height / pic.Height;
        double oldH = pic.Height;
        if (fX < fY)
        {
            pic.Width *= fX;
            if (pic.Height == oldH) // no change if aspect ratio is locked
                pic.Height *= fX;
            pic.Top += (height - pic.Height) / 2;
        }
        else
        {
            pic.Width *= fY;
            if (pic.Height == oldH) // no change if aspect ratio is locked
                pic.Height *= fY;
            pic.Left += (width - pic.Width) / 2;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-26
      • 2017-04-13
      • 2011-09-28
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 2011-04-27
      • 2020-06-06
      相关资源
      最近更新 更多