旋转图形?

Rob*_*Rob 11 c#

我有这个代码,绘制图像.

private void timer1_Tick(object sender, EventArgs e)
{
    Invalidate();
}

protected override void OnPaint(PaintEventArgs e)
{
    var tempRocket = new Bitmap(Properties.Resources.rocket);

    using (var g = Graphics.FromImage(tempRocket))
    {
        e.Graphics.DrawImage(tempRocket, 150, 150);
    }
}
Run Code Online (Sandbox Code Playgroud)

然而我该如何旋转呢?

jen*_*ent 28

public static Bitmap RotateImage(Bitmap b, float angle)
{
  //create a new empty bitmap to hold rotated image
  Bitmap returnBitmap = new Bitmap(b.Width, b.Height);
  //make a graphics object from the empty bitmap
  using(Graphics g = Graphics.FromImage(returnBitmap)) 
  {
      //move rotation point to center of image
      g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
      //rotate
      g.RotateTransform(angle);
      //move image back
      g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
      //draw passed in image onto graphics object
      g.DrawImage(b, new Point(0, 0)); 
  }
  return returnBitmap;
}
Run Code Online (Sandbox Code Playgroud)

  • 应该将`Graphics g`的创建烘焙到`using`语句中. (3认同)

Rei*_*ica 7

有一些重载Graphics.DrawImage采用三个点来确定目标的平行四边形,例如:

Graphics.DrawImage方法(Image,Point [])

备注

destPoints参数指定平行四边形的三个点.三点结构表示平行四边形的左上角,右上角和左下角.第四点从前三个推断出来形成平行四边形.

由图像参数表示的图像被缩放并剪切以适合由destPoints参数指定的平行四边形的形状.

MSDN上还有一篇文章描述了这种方法的用法:如何:旋转,反射和歪斜图像,使用以下代码示例.不幸的是,该示例通过使图像偏斜来使问题复杂化.

Point[] destinationPoints = {
          new Point(200, 20),   // destination for upper-left point of original
          new Point(110, 100),  // destination for upper-right point of original
          new Point(250, 30)};  // destination for lower-left point of original

Image image = new Bitmap("Stripes.bmp");

// Draw the image unaltered with its upper-left corner at (0, 0).
e.Graphics.DrawImage(image, 0, 0);

// Draw the image mapped to the parallelogram.
e.Graphics.DrawImage(image, destinationPoints);
Run Code Online (Sandbox Code Playgroud)

与使用该Graphics.Transform属性相比的主要差异是:

  • 此方法不允许您以度为单位指定旋转角度 - 您必须使用一些简单的三角函数来导出点.
  • 此转换仅适用于特定图像.
    • 好的,如果您只需要绘制一个旋转的图像而其他所有内容都是非旋转的,因为您之后不必重置Graphics.Transform.
    • 如果您想要将多个东西一起旋转(即旋转"相机"),则会很糟糕.