简体   繁体   English

C#在PictureBox上绘制

[英]C# Draw on a PictureBox

Suppose i have an PictureBox with image assigned to it, and i just want to draw a smaller bitmap above it. 假设我有一个分配了图像的PictureBox,而我只想在其上方绘制一个较小的位图。

This is my code: 这是我的代码:

 Bitmap a = Getimage();//just a small function generates a new image.
 Bitmap f = (Bitmap) pictureBox1.Image;//getting the picturebox image.
 Graphics g = Graphics.FromImage(f);
 g.DrawImage(a,150,200);//draws a on f at (150,200).
 PictureBox1.Image=f;

However, in my program it runs on a loop in a seperated thread, so im getting an Error: 但是,在我的程序中,它在单独的线程中循环运行,因此出现错误:

Object is in use elsewhere 对象在其他地方使用

Is there any way to draw directly to the Picturebox itself? 有没有办法直接绘制到Picturebox本身? instead of getting it's bitmap and draw, and assign again? 而不是获取位图并绘制,然后重新分配? Or at least how may i solve the above exception? 或者至少我该如何解决以上例外情况?

Thanks. 谢谢。

this will help you 这会帮助你

    public Form1()
    {
        InitializeComponent();
        new Thread(MyDraw).Start();
    }

    private void MyDraw()
    {
        while(true)
        {
            Invoke(new Action(DrawItem));
            Thread.Sleep(1000);
        }
    }

    private void DrawItem()
    {
        using (var graphics = Graphics.FromImage(pictureBox1.Image))
        {
            graphics.DrawString("Hello", new Font("Arial", 20), Brushes.Yellow, PointF.Empty);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM