[英]How to place maximum images in a blank Bitmap based on column/row input & margin variables and preserving aspect ratio of images
這可能是一個棘手的問題。
我只會追逐。 首先,我制作一個空白的位圖圖像:
Bitmap MasterImage = new Bitmap(PageSize.Width, PageSize.Height, PixelFormat.Format32bppArgb);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(MasterImage);
之后:基於列和行,我得到了要在空白位圖(頁面)中放置多少圖像的參數:
int numOfColumns=2; //(could be any value)
int numOfRows=4;
所以我們應該得到這樣的東西:
如果我在頂部圖像和左側圖像有一定的余量,我也會得到一個參數:
int PagetopMargin=0; //(could be any value)
int PageLeftMargin=0;
比我有一個名為: imagesPath
的變量,它是List<String>
類型,它包含圖像的完整路徑。
現在我遍歷圖像:
while (imagesPath.Count > 0)
{
Image image = Image.FromFile(imagesPath[0]);
//Logic comes here.
//after finishing processing and drawing images in Bitmap i remove image from list
imagesPath.RemoveAt(0);
}
我想要實現的是如何基於列/行和邊距變量以及保留圖像的長寬比,在該位圖頁面中放置最大圖像。 (因此圖像不會失真)。 如果遺留了一些圖像,這很好,我將繼續下一個空白位圖來放置它們。 只需將位圖空白圖像填滿即可。
這是一個函數,可將一個矩形擬合到另一個居中或未居中的矩形(左上對齊):
Rectangle FitToBox(Rectangle scr, Rectangle dest, bool centered)
{
var ratioX = (double)dest.Width / scr.Width;
var ratioY = (double)dest.Height / scr.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(scr.Width * ratio);
var newHeight = (int)(scr.Height * ratio);
if (!centered)
return new Rectangle(0, 0, newWidth, newHeight);
else
return new Rectangle((dest.Width - newWidth) / 2,
(dest.Height - newHeight) / 2, newWidth, newHeight);
}
它的基本數學取材於此 。
這是一個使用不同隨機值居中和未居中的測試台:
Random rnd = new Random();
int cols = rnd.Next(3) + 2;
int rows = rnd.Next(4) + 3;
int w = pan_dest.Width / cols;
int h = pan_dest.Height / rows;
using (Graphics G = pan_dest.CreateGraphics())
{
G.Clear(Color.White);
for (int c = 0; c < cols; c++)
for (int r = 0; r < rows; r++)
{
Rectangle rDest = new Rectangle(c * w, r * h, w, h);
Rectangle rSrc = new Rectangle(0, 0, rnd.Next(200) + 10, rnd.Next(200) + 10);
Rectangle rResult = FitToBox(rSrc, rDest, checkBox1.Checked);
Rectangle rDestPlaced = new Rectangle(c * w + (int)rResult.X,
r * h + rResult.Y, rResult.Width, rResult.Height);
using (Pen pen2 = new Pen(Color.SlateGray, 4f))
G.DrawRectangle(pen2, Rectangle.Round(rDest));
G.DrawRectangle(Pens.Red, rDestPlaced);
G.FillEllipse(Brushes.LightPink, rDestPlaced);
}
}
然后,您將像這樣繪制圖像:
G.DrawImage(someImageimg, rDestPlaced, rSrc, GraphicsUnit.Pixel);
這樣可以最大化圖像的大小 ,而不是注釋中指定的頁面上可以容納的圖像數 。 對於后者,您應該研究二維包裝 ..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.