我有自己的简单3d引擎类(myGraphics
),可将结果保存在Bitmap变量中。
然后将该位图放在PictureBox(PictureBox.Image = myGraphics.bmp
)
这很好用,当我需要在图纸上标记一些点时问题出现了。由于没有内置方法在位图上绘制字符串,我在类似的问题中遵循解决方案,现在我在Graphics
上得到myGraphics
变量,因此我可以在那里绘制数字。代码的重要部分如下:
public class myGraphics
{
public Graphics g;
public void initialize(int W, int H )
{
//sets some values
g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
}
public void draw()
{
// code to draw on myGraphics.bmp
markpoints();
}
public void markpoints()
{
if (draw_points) {
foreach (objecto ob in solidos) {
for (int p = 0; p < ob.viewpoints.Count; p++)
{
// determine position of text (x, y)
SolidBrush drawBrush = new SolidBrush(Color.Black);
g.DrawString(p.ToString(), new Font("Arial", 10), drawBrush, x, y);
g.Flush();
}
}
}
}
现在,如果我做对了,g.Flush()应该合并Bitmap上的Graphics g,但它没有那样工作,所以我得到了正确的图像,但没有刺痛。
我也试过这个:myGraphics.g = PictureBox.CreateGraphics();
来解决它。在调试模式下使用断点我意识到字符串确实出现在使用此方法的控件上,但在PictureBox更新后立即被删除。
那么,我怎么能解决这个问题,所以我可以得到图纸上显示的数字?
答案 0 :(得分:-2)
更新PictureBox.Image
后,图形将被清除。因此,必须在markpoints()
更新后立即从课外调用PictureBox.Image
。
另外,分配myGraphics.g = Picturebox.CreateGraphics()
不会工作,myGraphics.g上的更改不会更新到控件PictureBox。必须在paint事件上更新控件的图形,并将e.graphics
传递给markpoints
另外,g.flush()
不会将图形与Bitmap合并,实际上这个代码不需要
所以,最终解决方案:
public class myGraphics
{
// public Graphics g is no longer necessary
public void initialize(int W, int H ) { //sets some values}
public void draw() { // code to draw on myGraphics.bmp }
public void markpoints(Graphics graph)
{
if (draw_points) {
graph.SmoothingMode = SmoothingMode.AntiAlias;
graph.InterpolationMode = InterpolationMode.HighQualityBicubic;
graph.PixelOffsetMode = PixelOffsetMode.HighQuality;
foreach (objecto ob in solidos) {
for (int p = 0; p < ob.viewpoints.Count; p++)
{
// determine position of text (x, y)
SolidBrush drawBrush = new SolidBrush(Color.Black);
g.DrawString(p.ToString(), new Font("Arial", 10), drawBrush, x, y);
}
}
}
}
}
// Connect to picture box
myGraphics mg = new myGraphics()
Picturebox.Image = mg.bmp;
PictureBox.Invalidate(); // forces update of the control using paint event
private void PictureBox_Paint(object sender, PaintEventArgs e)
{
mg.markpoints(e.Graphics);
}