一个坐标点围绕任意中心点旋转--C#实现
假设对图片上任意点(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();