C# 在windows窗体中绘制矩形时出现问题
我是c#新手,不使用visual studio。相反,我使用C# 在windows窗体中绘制矩形时出现问题,c#,drawing,C#,Drawing,我是c#新手,不使用visual studio。相反,我使用csc.exe在命令提示符下编译我的c代码。我想在表格上画一些图像。位图中有一个红色矩形。位图本身位于picturebox中(pictureBox1.Image=(Image)bm;)。运行代码不会显示任何内容。但如果我将位图保存到文件中,然后使用该文件(pictureBox1.Image=I;)在表单上显示,它至少会显示一些肯定不是我绘制的矩形的内容 我不知道在哪里编辑。谢谢你的帮助。多谢各位 这是我的密码 using System;
csc.exe
在命令提示符下编译我的c代码。我想在表格上画一些图像。位图中有一个红色矩形。位图本身位于picturebox中(pictureBox1.Image=(Image)bm;
)。运行代码不会显示任何内容。但如果我将位图保存到文件中,然后使用该文件(pictureBox1.Image=I;
)在表单上显示,它至少会显示一些肯定不是我绘制的矩形的内容
我不知道在哪里编辑。谢谢你的帮助。多谢各位
这是我的密码
using System;
using System.Drawing;
using System.Windows.Forms;
class myapp: Form
{
public PictureBox pictureBox1;
public myapp(string[] args)
{
Graphics g = CreateGraphics();
Pen pen = new Pen(Color.Red, 5);
Rectangle myRectangle = new Rectangle(100,100, 250, 200);
g.DrawRectangle(pen, myRectangle);
Bitmap bm = new Bitmap( 500,500,g );
g.Dispose();
bm.Save("333.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
Image i = Image.FromFile("333.jpg");
pictureBox1 = new PictureBox();
pictureBox1.Image = (Image)bm;
//pictureBox1.Image = i;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
this.Controls.Add( pictureBox1 );
}
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.Run(new myapp(args));
}
}
您没有初始化任何组件或任何东西。我不知道您为什么选择不使用VS,但我强烈建议您在可能的情况下更改该决定。有一个功能强大的免费版本,VS为您做了很多winforms脚手架,所以您a)不需要自己做,b)一旦您可以学习,就可以看到VS是如何做的。谢谢您的回答@itsme86。我的系统很旧,vs很重,我的电脑只会在打开vs时减慢速度。如果我在代码中放入InitializeComponent()
,则会出现错误上下文中不存在。我该怎么办?Winforms graphics基本规则#1:永远不要使用控件。CreateGraphics
!切勿尝试缓存图形
对象!使用Graphics g=Graphics.FromImage(bmp)
或在控件的Paint
事件中,使用e.Graphics
参数将bmp绘制到位图中要保存,请使用panel1.DrawToBitmap!-至于winforms应用程序的正确代码:请搜索完整的示例!谢谢@TaW,油漆事件解决了问题。