private void Button1_Click(object sender, EventArgs e) { Graphics graphics = this.CreateGraphics(); graphics.Clear(Color.White); //裝入圖片 資源 //Bitmap image = new Bitmap(WindowsFormsApplication1.Properties.Resources.image_101); Bitmap image = new Bitmap(HZH_Controls.Properties.Resources.alarm); //獲取當前窗口的中心點 Rectangle rect = new Rectangle(0, 0, this.ClientSize.Width, this.ClientSize.Height); PointF center = new PointF(rect.Width / 2, rect.Height / 2); float offsetX = 0; float offsetY = 0; offsetX = center.X - image.Width / 2; offsetY = center.Y - image.Height / 2; //構造圖片顯示區域:讓圖片的中心點與窗口的中心點一致 RectangleF picRect = new RectangleF(offsetX, offsetY, image.Width, image.Height); PointF Pcenter = new PointF(picRect.X + picRect.Width / 2, picRect.Y + picRect.Height / 2); Color c = Color.FromArgb(200, 200, 200); //讓圖片繞中心旋轉一周 for (int i = 360; i > 0; i -= 10) { // 繪圖平面以圖片的中心點旋轉 graphics.TranslateTransform(Pcenter.X, Pcenter.Y); graphics.RotateTransform(i); //恢復繪圖平面在水平和垂直方向的平移 graphics.TranslateTransform(-Pcenter.X, -Pcenter.Y); //繪制圖片並延時 graphics.DrawImage(image, picRect); Thread.Sleep(100); graphics.Clear(c); //重置繪圖平面的所有變換 graphics.ResetTransform(); } }
以上代碼是同步的,用戶體驗不好。
下面是經過改善的異步方法
private void Button1_Click(object sender, EventArgs e) { Graphics graphics = this.CreateGraphics(); graphics.Clear(Color.White); //裝入圖片 資源 //Bitmap image = new Bitmap(WindowsFormsApplication1.Properties.Resources.image_101); Bitmap image = new Bitmap(HZH_Controls.Properties.Resources.alarm); //獲取當前窗口的中心點 Rectangle rect = new Rectangle(0, 0, this.ClientSize.Width, this.ClientSize.Height); PointF center = new PointF(rect.Width / 2, rect.Height / 2); float offsetX = 0; float offsetY = 0; offsetX = center.X - image.Width / 2; offsetY = center.Y - image.Height / 2; //構造圖片顯示區域:讓圖片的中心點與窗口的中心點一致 RectangleF picRect = new RectangleF(offsetX, offsetY, image.Width, image.Height); PointF Pcenter = new PointF(picRect.X + picRect.Width / 2, picRect.Y + picRect.Height / 2); Action<Graphics, PointF, Bitmap, RectangleF> action = test;//聲明委托 action.BeginInvoke(graphics, Pcenter, image, picRect,null,null);//異步調用 } static void test(Graphics graphics,PointF Pcenter,Bitmap image, RectangleF picRect) { //讓圖片繞中心旋轉一周 Color c = Color.FromArgb(200, 200, 200); for (int i = 360; i > 0; i -= 10) { // 繪圖平面以圖片的中心點旋轉 graphics.TranslateTransform(Pcenter.X, Pcenter.Y); graphics.RotateTransform(i); //恢復繪圖平面在水平和垂直方向的平移 graphics.TranslateTransform(-Pcenter.X, -Pcenter.Y); //繪制圖片並延時 graphics.DrawImage(image, picRect); Thread.Sleep(100); graphics.Clear(c); //重置繪圖平面的所有變換 graphics.ResetTransform(); } }