假設對圖片上任意點(x,y),繞一個坐標點(rx0,ry0)逆時針旋轉RotaryAngle角度后的新的坐標設為(x', y'),有公式: x'= (x - rx0)*cos(RotaryAngle) + (y - ry0)*sin(RotaryAngle) + rx0 ; y'=-(x - rx0)*sin(RotaryAngle) + (y - ry0)*cos(RotaryAngle) + ry0 ; [csharp] view plaincopy /// <summary> /// 對一個坐標點按照一個中心進行旋轉 /// </summary> /// <param name="center">中心點</param> /// <param name="p1">要旋轉的點</param> /// <param name="angle">旋轉角度,笛卡爾直角坐標</param> /// <returns></returns> private Point PointRotate(Point center, Point p1, double angle) { Point tmp = new Point(); double angleHude = angle * Math.PI / 180;/*角度變成弧度*/ double x1 = (p1.X - center.X) * Math.Cos(angleHude) + (p1.Y - center.Y ) * Math.Sin(angleHude) + center .X; double y1 = -(p1.X - center.X) * Math.Sin(angleHude) + (p1.Y - center.Y) * Math.Cos(angleHude) + center.Y; tmp.X = (int)x1; tmp.Y = (int)y1; return tmp; }
另一種旋轉的方法:
private void Form1_Paint(object sender, PaintEventArgs e) { Graphics graphics = e.Graphics; var picRect = new RectangleF(200, 200, 100, 50); PointF[] points = new PointF[] { // 將原來四邊形的4個頂點坐標放入數組 picRect.Location, new PointF(picRect.Right, picRect.Top), new PointF(picRect.Right, picRect.Bottom), new PointF(picRect.Left, picRect.Bottom) }; graphics.DrawPolygon(new Pen(Color.Red), points); Matrix matrix=new Matrix(); //更改坐標系 graphics.TranslateTransform(100, 100); //旋轉角度 graphics.RotateTransform(10); //恢復坐標系 graphics.TranslateTransform(-100, -100); //獲取旋轉后的坐標 graphics.Transform.TransformPoints(points); graphics.DrawPolygon(new Pen(Color.Red), points); }
//獲取旋轉中心
//var center = new PointF(rectBorder.Width/2, rectBorder.Height/2);
////矩形左上坐標
//float offsetX = 0;
//float offsetY = 0;
//offsetX = center.X - rectBorder.Width/2;
//offsetY = center.Y - rectBorder.Height/2;
////要畫的圖
//var picRect = new RectangleF(offsetX, offsetY, rectBorder.Width, rectBorder.Height);
//var Pcenter = new PointF(picRect.X + picRect.Width/2, picRect.Y + picRect.Height/2);
////讓圖片繞中心旋轉一周
////for (int i = 0; i < 361; i += 10)
////{
//var changeRect = new Rectangle((int) picRect.X, (int) picRect.Y, (int) picRect.Width,
// (int) picRect.Height);
////繪圖平面以圖片的中心點旋轉
//graphics.TranslateTransform(Pcenter.X, Pcenter.Y);
//graphics.RotateTransform(_ShapeExAngle);
////恢復繪圖平面在水平和垂直方向的平移
//graphics.TranslateTransform(-Pcenter.X, -Pcenter.Y);
////繪制圖片並延時
//graphics.DrawRectangle(borderPen, changeRect);
////重置繪圖平面的所有變換
//graphics.ResetTransform();
