簡體   English   中英

將圖像放在PdfPCell的中心,並溢出到單元格iTextSharp

[英]Place image in the center of PdfPCell and have overflow to cell iTextSharp

我正在嘗試使用ItextSharp將圖像放置在PdfPCell中。 我想將圖像放置在vert / horiz中心,並使圖像適合中心裁剪(以隱藏圖像的其余部分),我發現的唯一方法是ScaleAbsolute,它可以拉伸圖像並使其看起來不好,另一個是ScaleToFit哪個不會填滿單元格的所有空間。 有什么方法可以在單元格中顯示圖像(例如overflor:hidden html) 在此處輸入圖片說明

@mkl您好。 我嘗試您的解決方案,然后.... WOW看起來像是在正確的方式下正常工作。 唯一的問題是,該代碼適用於人像圖像,而對風景圖像幾乎適用。 有什么我可以解決的嗎? (只有在正方形區域的風景圖像上才會發生這種情況,代碼在高度或高度區域上都適用

在此處輸入圖片說明

正如Bruno在評論中已經提到的那樣,您必須將單元格事件用於自定義縮放和裁剪任務。

也就是說,單元格最初是沒有圖像的“布局”,完成后,將使用單元格的位置和尺寸以及表格畫布觸發單元格事件。 現在,您可以按需要繪制圖像,縮放(或旋轉或傾斜,...)並任意裁剪。

當然,這確實意味着您必須確保表單元格不會折疊(畢竟在“布局”期間它是空的),例如通過設置FixedHeight或由相鄰單元格強制設置所需的高度。


例如,如果您拍攝此圖像:

威利,一個CKCS

並希望將其放入一個全高單列表中的高度的四倍的單元格中,應用您描述的縮放和裁剪,您可以像這樣進行操作(假設document是您的Document實例):

Image itextImage = RETRIEVE YOUR IMAGE AS ITEXTSHARP IMAGE;

PdfPCell cell = new PdfPCell()
{
    FixedHeight = (document.PageSize.Width - document.LeftMargin - document.RightMargin) / 4,
    CellEvent = new ImageEvent(itextImage)
};

PdfPTable table = new PdfPTable(1);
table.WidthPercentage = 100;
table.AddCell("Above the image");
table.AddCell(cell);
table.AddCell("Below the image");
document.Add(table);

與細胞事件助手類

class ImageEvent : IPdfPCellEvent
{
    Image image;

    public ImageEvent(Image image)
    {
        this.image = image;
    }

    public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
    {
        PdfContentByte canvas = canvases[0];

        float scaleX = position.Width / image.Width;
        float scaleY = position.Height / image.Height;
        float scale = Math.Max(scaleX, scaleY);
        image.ScaleToFit(image.Width * scale, image.Height * scale);

        image.SetAbsolutePosition((position.Left + position.Right - image.ScaledWidth) / 2, (position.Bottom + position.Top - image.ScaledHeight) / 2);

        canvas.SaveState();
        canvas.Rectangle(position.Left, position.Bottom, position.Width, position.Height);
        canvas.Clip();
        canvas.NewPath();
        canvas.AddImage(image);
        canvas.RestoreState();
    }
}

(如您所見, scale因子被選擇為所需布局的scaleXscaleY的最大值。如果您選擇最小值,則結果將是原始示例的ScaleToFit版本。或者如果選擇的值高一點(比最大值大),您甚至可以放大圖像中心。)

結果看起來像這樣:

表格截圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM