WPF GDI+画图

来源:互联网 发布:qq游戏hd登陆网络异常 编辑:程序博客网 时间:2024/05/02 00:33
文章内的代码主要是介绍了如何通过GDI+的方式在WPF中进行画图。


    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private System.Drawing.Image bitmap = null;
        private MemoryStream mos = null;
        private int lastX = -1;
        private double lastY = -1;
        Thread t = null;
        public MainWindow()
        {
            
            mos = new MemoryStream();
            InitializeComponent();
            bitmap = new Bitmap(800,600) ;
            t = new Thread(CreateDataAndDraw);
            t.IsBackground = true;
            t.Start();
            this.img.MouseDown += img_MouseDown;
            this.img.MouseUp += img_MouseUp;
           
        }


        void img_MouseUp(object sender, MouseButtonEventArgs e)
        {
            locker.Set();
        }


        void img_MouseDown(object sender, MouseButtonEventArgs e)
        {
            locker.Reset();
        }


        public static ManualResetEvent locker = new ManualResetEvent(true);
        public void CreateDataAndDraw() 
        {


            while (true)
            {


                    
                    Thread.Sleep(10);
                    locker.WaitOne();
                
                   
                    double y = new Random().NextDouble() * 200 + 200;
                    this.Dispatcher.Invoke(() => 
                    {
                        DrawTest(lastX+5, y);
                    });
                    lastX += 5;
                    lastY = y;
                    locker.Set();
            }
            
        }
        public void DrawTest(int pointX, double pointY) 
        {
            Graphics g = Graphics.FromImage(bitmap);
            g.DrawLine(Pens.AliceBlue, new PointF(lastX, (float)lastY), new PointF(pointX, (float)pointY));
            g.Save();
            bitmap.Save(mos, ImageFormat.Bmp);
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = mos;
            bitmapImage.EndInit();
            img.Source = bitmapImage;  
            
        }
    }
0 0