Why might Graphics.RotateTransform() not be applie

2019-09-06 13:18发布

I have the following function:

static private Image CropRotate(Image wholeImage, Rectangle cropArea)
{
    Bitmap cropped = new Bitmap(cropArea.Width, cropArea.Height);

    using(Graphics g = Graphics.FromImage(cropped))
    {
        g.DrawImage(wholeImage, new Rectangle(0, 0, cropArea.Width, cropArea.Height), cropArea, GraphicsUnit.Pixel);
        g.RotateTransform(180f);
    }
    return cropped as Image;
}

It's supposed to crop an image, then rotate the resulting sub-image. In actuality though, it only performs the crop.

Why is RotateTransform() not being applied?

2条回答
疯言疯语
2楼-- · 2019-09-06 13:57

The RotateTransform call alters the current transform matrix, which has an effect on all subsequent operations. It does not transform the already output operations at all. This is the same for any of the operations that change the transform matrix (like ScaleTransform).

Make sure you call these before you perform the operations you want transformed - in this case, before the call to DrawImage.

You can use this to do something like

  1. Draw (not rotated or scaled)
  2. Rotate (only changes transform matrix)
  3. Scale (only changes transform matrix)
  4. Draw (now rotated and scaled)
  5. ClearTransform (only changes transform matrix)
  6. Draw (not rotated or scaled)

the first and last draw outputs will not be transformed, but the middle one would be affected by both the rotate and scale (in that order).

查看更多
家丑人穷心不美
3楼-- · 2019-09-06 14:23

Have you tried putting the RotateTransform() before the DrawImage()? The example on the msdn page shows the transformation being applied before any drawing is done.

查看更多
登录 后发表回答