我想在Windows窗体上打印图像,但是我想在页面上打印尽可能大的图像而不破坏其宽高比。就像我要在A4纸上打印一个简单的正方形一样,使用以下脚本将其变成矩形:
private void Page(object sender, PrintPageEventArgs e)
{
Bitmap i = image;
if(e.PageBounds.Height > e.PageBounds.Width)
{
if (i.Width > i.Height)
i.RotateFlip(RotateFlipType.Rotate90FlipNone);
}
else if(e.PageBounds.Width > e.PageBounds.Height)
{
if (i.Height > i.Width)
i.RotateFlip(RotateFlipType.Rotate90FlipNone);
}
e.Graphics.DrawImage(i, new Rectangle(0, 0, e.PageBounds.Width, e.PageBounds.Height));
i.Dispose();
}
原件: 500x500 square
我得到了什么(PDF格式): A rectangle on the A4 paper
另一个例子:
打印:Print image
我不想破坏图像的长宽比
答案 0 :(得分:1)
尝试一下:
private void Page(object sender, PrintPageEventArgs e)
{
using (Bitmap i = image) //are you *really sure* you want to dispose this after printing?
{
var pageRatio = e.PageBounds.Width / (double)e.PageBounds.Height;
var imageRatio = i.Width / (double)i.Height;
//do we need to rotate?
if ( (pageRatio < 1 && imageRatio > 1) || (pageRatio < 1 && imageRatio > 1))
{
i.RotateFlip(RotateFlipType.Rotate90FlipNone);
imageRatio = i.Width / (double)i.Height; //ratio will have changed after rotation
}
var scale = 1.0D;
//do we need to scale?
if (pageRatio > imageRatio)
{ //the page is wider than the image, so scale to the height
scale = e.PageBounds.Height / (double)i.Height;
}
else if (pageRatio < imageRatio)
{ //the page is narrower than the image, so scale to width
scale = e.PageBounds.Width / (double)i.Width;
}
var W = (int)(scale * i.Width);
var H = (int)(scale * i.Height);
e.Graphics.DrawImage(i, new Rectangle(0, 0, W, H));
}
}
这将始终从左上角绘制。如果要使其居中,则需要进行其他调整:
private void Page(object sender, PrintPageEventArgs e)
{
using (Bitmap i = image) //are you *really sure* you want to dispose this after printing?
{
var pageRatio = e.PageBounds.Width / (double)e.PageBounds.Height;
var imageRatio = i.Width / (double)i.Height;
//do we need to rotate?
if ( (pageRatio < 1 && imageRatio > 1) || (pageRatio < 1 && imageRatio > 1))
{
i.RotateFlip(RotateFlipType.Rotate90FlipNone);
imageRatio = i.Width / (double)i.Height; //ratio will have changed after rotation
}
int T = 0, L = 0; //top, left
var scale = 1.0D;
int W = i.Width, H = i.Height;
//do we need to scale?
if (pageRatio > imageRatio)
{ //the page is wider than the image, so scale to the height
scale = e.PageBounds.Height / (double)i.Height;
W = (int)(scale * i.Width);
H = (int)(scale * i.Height);
L = (e.PageBounds.Width - W)/2;
}
else if (pageRatio < imageRatio)
{ //the page is narrower than the image, so scale to width
scale = e.PageBounds.Width / (double)i.Width;
W = (int)(scale * i.Width);
H = (int)(scale * i.Height);
T = (e.PageBounds.Height - H)/2;
}
e.Graphics.DrawImage(i, new Rectangle(L, T, W+L, H+T));
}
}
重要的是宽度和高度都调整为相同的比例 ...,即乘以相同的数字。