C# Forms Picturebox 显示纯色而不是图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1807004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:01:31  来源:igfitidea点击:

C# Forms Picturebox to show a solid color instead of an image

c#windowsimage

提问by dkarzon

Im making a little app to display the pictures of guests as they scan their cards. But i want to to display blank green or red (green if the guest exists without a photo and red if they dont exist)

我正在制作一个小应用程序来显示客人扫描卡片时的照片。但我想显示空白的绿色或红色(如果客人没有照片,则为绿色,如果不存在则为红色)

But i cant figure out how to create a blank colour image.

但我不知道如何创建一个空白的彩色图像。

Bitmap bmRed = new Bitmap(imgbox.Width, imgbox.Height, PixelFormat.Format24bppRgb);
imgbox.Image = bmRed;

Thats the code i have at the moment and it just makes the box black. imgbox is a PictureBox

这就是我目前拥有的代码,它只会使框变黑。imgbox 是一个图片框

采纳答案by Jay Riggs

Don't use an image - set the BackColor property of the PictureBox:

不要使用图像 - 设置 PictureBox 的 BackColor 属性:

imgBox.BackColor = Color.Red;

回答by Andrew Keith

create a graphics context and draw using it.

创建一个图形上下文并使用它进行绘制。

using(Graphics g = Graphics.FromImage(bmRed))
{
  g.FillRectangle(new SolidBrush(Color.Red),0,0,imgbox.Width,imgbox.Height);
}

回答by micahtan

How about setting the background color directly?

直接设置背景颜色怎么样?

imgbox.BackColor = Color.Red;

回答by Michael_S_

To prevent null pointer exception, create a blank bmp

为防止空指针异常,创建一个空白的bmp

myPicBox.Image = new Bitmap(myPicBox.Width, myPicBox.Height);
Graphics graphics = Graphics.FromImage(myPicBox.Image);

Brush brush = new SolidBrush(Color.Gray);

graphics.FillRectangle(brush, new System.Drawing.Rectangle(0, 0, myPicBox.Width, myPicBox.Height));

回答by Srivishnu

Single statement:

单一声明:

Graphics.FromImage(PicBox.Image=new bitmap(PicBox.Size)).FillRectangle(Brushes.Red,new Rectangle (Point.EMPTY,PicBox.Size));