我想围绕给定点旋转位图,并使该点成为位图的新中心。
这是我首先尝试的
Bitmap rotate(Bitmap img, float angle, int cx, int cy)
{
Bitmap result = new Bitmap(img.Width, img.Height);
int middleX = img.Width / 2,
middleY = img.Height / 2;
using (Graphics g = Graphics.FromImage(result))
{
g.Clear(Color.Black);
g.TranslateTransform(cx, cy);
g.RotateTransform(angle);
g.TranslateTransform(-cx, -cy);
g.TranslateTransform(middleX - cx, middleY - cy); //shift (cx, cy) to be at the center, does not work
g.DrawImage(originalImage, new Point(0, 0));
}
return result;
}
但是当我旋转后平移图像时,平移在原始空间中而不是在新的旋转空间中进行,并且输出不正确。 我基本上尝试了所有我想不到的事情的组合。搜索结果仅描述如何围绕一个点旋转。
旋转45度后,应平移图像,使红点成为图像的中心
答案 0 :(得分:-1)
您必须将矩阵顺序设置为“追加”以进行最终翻译。我不知道为什么这使它起作用。实际上,我只是蛮力尝试了所有可行的方法来完成所有工作。我仍然会对发生的情况感兴趣。
Bitmap rotate(Bitmap img, float angle, int cx, int cy)
{
Bitmap result = new Bitmap(img.Width, img.Height);
int mx = img.Width / 2,
my = img.Height / 2;
using (Graphics g = Graphics.FromImage(result))
{
g.Clear(Color.Black);
g.TranslateTransform(cx, cy);
g.RotateTransform(angle);
g.TranslateTransform(-cx, -cy);
g.TranslateTransform(mx - cx, my - cy, MatrixOrder.Append);
g.DrawImage(originalImage, new Point(0, 0));
}
return result;
}