如何防止粘贴的图像溢出其边界? [英] How can I prevent the pasted image from overflowing its boundaries?

查看:98
本文介绍了如何防止粘贴的图像溢出其边界?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

不幸的是,该图像对于该范围(当前第1到第4行,第16列)太大.它没有进行礼貌的操作并按比例缩小以适应规定的范围,而是溢出并超出了指定的垂直和水平位置.

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"?

推荐答案

我从一个相关问题的适应中得到了答案

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

这篇关于如何防止粘贴的图像溢出其边界?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆