C#如何旋转PictureBox控件并保证标注矩形相对位置不变
问题原因
- 旋转中心选择错误:当前代码是围绕每个标注矩形自身的中心旋转,但图片是围绕PictureBox内缩放显示后的整张图片的中心旋转的,两者旋转中心不一致,必然导致标注错位
- 存在重复绘制逻辑:Paint事件中你先绘制了旋转后的矩形,又绘制了一次未旋转的矩形,属于多余逻辑,也会干扰显示效果
- 没有对齐图片旋转后的坐标系映射:标注的原始坐标是对应未旋转的原始图片的,旋转后需要基于整张图片的旋转中心做坐标变换,不能单独变换标注自身
修复方案
首先需要先获取Zoom模式下PictureBox内图片实际的显示区域和旋转中心,再统一基于该中心做标注的旋转变换,删除多余的绘制逻辑。
第一步:新增辅助方法计算图片实际显示参数
首先写一个工具方法获取Zoom模式下图片的实际显示边界、缩放比例和旋转中心:
// 计算PictureBox在Zoom模式下的图片实际显示区域和缩放比 private void GetImageDisplayInfo(PictureBox pb, out RectangleF displayRect, out float scale) { displayRect = RectangleF.Empty; scale = 1f; if (pb.Image == null) return; float imgW = pb.Image.Width; float imgH = pb.Image.Height; float ctrlW = pb.ClientSize.Width; float ctrlH = pb.ClientSize.Height; // 计算Zoom等比缩放比例 scale = Math.Min(ctrlW / imgW, ctrlH / imgH); float displayW = imgW * scale; float displayH = imgH * scale; // 计算居中显示的偏移量 float offsetX = (ctrlW - displayW) / 2; float offsetY = (ctrlH - displayH) / 2; displayRect = new RectangleF(offsetX, offsetY, displayW, displayH); }
第二步:修改Paint事件逻辑
删掉重复绘制的代码,将旋转中心改为整张图片的显示中心:
private void picZoom_Paint(object sender, PaintEventArgs e) { if (picZoom.Image == null || Annotations.Items.Count == 0) return; // 获取图片显示信息和旋转中心 GetImageDisplayInfo(picZoom, out RectangleF imgDisplayRect, out _); PointF rotateCenter = new PointF( imgDisplayRect.Left + imgDisplayRect.Width / 2, imgDisplayRect.Top + imgDisplayRect.Height / 2 ); for (int i = 0; i < Annotations.Items.Count; i++) { // 获得标注对应未旋转图片的缩放后控件坐标 Rectangle scaledRect = functions.ZoomRectangle(Annotations.Items[i].Box, picZoom, true); using (Matrix matrix = new Matrix()) { // 围绕整张图片的中心旋转,而非标注自身中心 matrix.RotateAt(RotationgAngle, rotateCenter); e.Graphics.Transform = matrix; e.Graphics.FillRectangle(new SolidBrush(c), scaledRect); e.Graphics.ResetTransform(); } } }
第三步:优化旋转角度累计逻辑
旋转图片时对角度取模,避免数值溢出:
Image img = picZoom.Image; img.RotateFlip(RotateFlipType.Rotate90FlipXY); picZoom.Image = img; // 角度超过360度取模,避免数值过大 RotationgAngle = (RotationgAngle + 90) % 360;
内容的提问来源于stack exchange,提问作者RickInWestPalmBeach
相关产品推荐
相关产品推荐

