how to draw an image with PictureBoxSizeMode.Zoom

In my application I need to print employee photo as ID Badge .I have used picture box control and sizemode as PictureBoxSizeMode.StretchImage. When printing this, the photo gets wider according to the Picture box Width and Height. But the photo doesn’t look like as an original one. Its perfect when I set sizemode as PictureBoxSizeMode.Zoom in designer window. But while printing, the result will be same as before. There is no effect.

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

The above code will execute when the PrintPage event is Triggered

Upvotes: 0

Views: 2882

Answers (2)

King King
King King

Reputation: 63327

I think before clicking on the print button, you can try capturing the bitmap of your PictureBox in Zoom mode like this:

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

Upvotes: 1

Monika
Monika

Reputation: 2210

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

To test it on your form perfectly, you should also have to set ResizeRedraw = true and enable DoubleBuffered:

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

Upvotes: 0

Related Questions