2013-11-26 68 views
0

在我的應用程序中,我需要將員工照片打印爲ID徽章。我使用圖片框控件和sizemode作爲PictureBoxSizeMode.StretchImage。 打印時,根據圖片框的寬度和高度,照片變寬。但照片看起來不像原來的那樣。 當我在設計器窗口中將sizemode設置爲PictureBoxSizeMode.Zoom時,它非常完美。但是在印刷過程中,結果與以前相同。沒有效果。如何使用PictureBoxSizeMode.Zoom繪製圖像

PictureBox pict = (PictureBox)ctrl; 
pict.SizeMode = PictureBoxSizeMode.Zoom; 
RectangleF rect = new RectangleF(pict.Location.X, pict.Location.Y, pict.Width, pict.Height); 
e.Graphics.DrawImage(pict.Image, rect); 

上面的代碼執行時PrintPage事件被觸發

+0

SizeMode根本不會影響圖像,只有PictureBox用來繪製圖像的Graphics.DrawImage()調用。你將不得不在你自己的代碼中重現。否則通過使用Graphics.ScaleTransform() –

回答

-1
//The Rectangle (corresponds to the PictureBox.ClientRectangle) 
//we use here is the Form.ClientRectangle 
//Here is the Paint event handler of your Form1 
private void Form1_Paint(object sender, EventArgs e){ 
    ZoomDrawImage(e.Graphics, yourImage, ClientRectangle); 
} 
//use this method to draw the image like as the zooming feature of PictureBox 
private void ZoomDrawImage(Graphics g, Image img, Rectangle bounds){ 
    decimal r1 = (decimal) img.Width/img.Height; 
    decimal r2 = (decimal) bounds.Width/bounds.Height; 
    int w = bounds.Width; 
    int h = bounds.Height; 
    if(r1 > r2){ 
    w = bounds.Width; 
    h = (int) (w/r1); 
    } else if(r1 < r2){ 
    h = bounds.Height; 
    w = (int) (r1 * h); 
    } 
    int x = (bounds.Width - w)/2; 
    int y = (bounds.Height - h)/2; 
    g.DrawImage(img, new Rectangle(x,y,w,h)); 
} 

要測試表單上的完美,你也應該有設置ResizeRedraw = TRUE,使DoubleBuffered:

public Form1(){ 
    InitializeComponent(); 
    ResizeRedraw = true; 
    DoubleBuffered = true; 
} 
+2

簡單做對不起,但我已經意識到,這段代碼看起來非常相同,我之前發佈的代碼(不長)在這個答案http://stackoverflow.com/questions/20101882/picturebox -zoom-mode-effect-with-graphics-object/20107316#20107316? –

+2

@ King - 它違反了本網站的許可條款。你可能需要解釋一下。要求是指向原始帖子的鏈接以及指向該帖子作者個人資料的鏈接。 –

+1

[This is off off plagiarism](http://stackoverflow.com/a/20107316)。 –

1

我覺得在點擊打印按鈕之前,你可以嘗試在Zoom模式下捕獲你的PictureBox的位圖,如下所示:

PictureBox pict = (PictureBox)ctrl; 
pict.SizeMode = PictureBoxSizeMode.Zoom; 
var bm = new Bitmap(pict.ClientSize.Width, pict.ClientSize.Height); 
pict.DrawToBitmap(bm, pict.ClientRectangle); 
e.Graphics.DrawImage(bm, pict.Bounds);