[英]How can I resize the image to fit the picturebox?
I'm trying to resize the image to fit the PictureBox size but it's not working.我正在尝试调整图像大小以适合 PictureBox 大小,但它不起作用。 I added a method resizeImage
but no matter what size I give the result is the same.我添加了一个方法resizeImage
但无论我给出什么大小,结果都是一样的。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Bitmap myBitmap = CreateNonIndexedImage(new Bitmap(@"d:\drawplane1.jpg"));
resizeImage(myBitmap, new Size(1, 1));
// Draw myBitmap to the screen.
e.Graphics.DrawImage(myBitmap, 0, 0, myBitmap.Width,
myBitmap.Height);
// Set each pixel in myBitmap to black.
for (int Xcount = 0; Xcount < myBitmap.Width; Xcount++)
{
for (int Ycount = 0; Ycount < myBitmap.Height; Ycount++)
{
myBitmap.SetPixel(Xcount, Ycount, Color.Black);
}
}
// Draw myBitmap to the screen again.
e.Graphics.DrawImage(myBitmap, myBitmap.Width, 0,
myBitmap.Width, myBitmap.Height);
}
public Bitmap CreateNonIndexedImage(Image src)
{
Bitmap newBmp = new Bitmap(src.Width, src.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
using (Graphics gfx = Graphics.FromImage(newBmp))
{
gfx.DrawImage(src, 0, 0);
}
return newBmp;
}
public static Image resizeImage(Image imgToResize, Size size)
{
return (Image)(new Bitmap(imgToResize, size));
}
}
No mater what size I put in the line:无论我放入什么尺寸:
resizeImage(myBitmap, new Size(1, 1));
..the image is too big inside the pictureBox: I tried 10,10
then 1,1
for testing but it's not changing the image size. ..图片框内的图像太大:我尝试了10,10
然后1,1
进行测试,但它没有改变图像大小。
This is the original image:这是原始图像:
Original image file: https://imgur.com/a/umegyk1原图文件: https://imgur.com/a/umegyk1
Try setting the SizeMode
of your PictureBox
to PictureSizeMode.Zoom
or PictureSizeMode.StretchImage
and see if it helps.尝试将PictureBox
的SizeMode
设置为PictureSizeMode.Zoom
或PictureSizeMode.StretchImage
看看是否有帮助。 Either through your properties editor or in code.通过您的属性编辑器或代码。
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
Your code has two issues:您的代码有两个问题:
SizeMode
property您不使用SizeMode
属性Paint
event instead of just setting the Image
property您在Paint
事件中绘制图像,而不仅仅是设置Image
属性If you want to draw the image in Paint
(eg. because it is an animation, whose frames are generated rapidly), then you don't need a PictureBox
, a simple Panel
will also do it.如果您想在Paint
中绘制图像(例如,因为它是一个 animation,其帧生成速度很快),那么您不需要PictureBox
,一个简单的Panel
也可以做到。
But if you generate the image once, then just assign it to the Image
property, set the SizeMode
for scaling and PictureBox
will care about the rest但是,如果您生成一次图像,则只需将其分配给Image
属性,设置SizeMode
进行缩放, PictureBox
将关心 rest
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.