How can I prevent the pasted image from overflowing its boundaries?

℡╲_俬逩灬. 提交于 2019-12-25 09:13:13

问题


I insert an image into an Excel range like so:

    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);

Unfortunately, the image is too large for that range (currently row 1 to row 4, column 16). Instead of doing the polite thing and scaling itself down to fit the prescribed bounds, it spills out and over its assigned vertical and horizontal spot.

How can I get the image to scale down and restrict itself to its "box"?


回答1:


I got the answer from adapting one at a related question here.

As long as I make the range large enough, this works:

    . . .
    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;
    }
}


来源:https://stackoverflow.com/questions/35899391/how-can-i-prevent-the-pasted-image-from-overflowing-its-boundaries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!