问题
When you load an image into a PictureBox there is a zoom for the image placement, how do I achieve that same effect with a graphics object?
回答1:
I think you mean you want to draw some Image
yourself in a Rectangle
and using some Graphics
object like as the PictureBox
renders its Image in Zoom
mode. Try the following code. I suppose you want to draw the Image
on a Form, the drawing code should be added in a Paint
event handler of your form:
//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;
}
来源:https://stackoverflow.com/questions/20101882/picturebox-zoom-mode-effect-with-graphics-object