根据用户控件旋转和缩放矩形 [英] Rotate and Scale rectangle as per user control

查看:95
本文介绍了根据用户控件旋转和缩放矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有大小为300 * 200的UserControl.和尺寸为300 * 200的矩形.

I have UserControl of Size 300*200. and rectangle of size 300*200.

graphics.DrawRectangle(Pens.Black, 0, 0, 300, 200);

当我在userControl中将矩形旋转30度时,我得到了旋转的矩形,但是矩形过大.

When I rotate rectangle in userControl by 30 degree, I get rotated rectangle but it is outsized.

PointF center = new PointF(150,100);
graphics.FillRectangle(Brushes.Black, center.X, center.Y, 2, 2); // draw center point.

using (Matrix matrix = new Matrix())
{
      matrix.RotateAt(30, center);
      graphics.Transform = matrix;
      graphics.DrawRectangle(Pens.Black, 0, 0, 300, 200);
      graphics.ResetTransform();
}

我希望像实际结果一样适合矩形.在此处检查图像

I want to fit rectangle like actual result.Check Image here

任何人都可以对此解决方案.

Can anyone have solution about this.

谢谢.

推荐答案

与其说是编程,不如说是一个数学问题.

It's more of a math question than programming one.

计算以弧度为单位旋转任意角度的任何矩形的合并框.

Calculate bouning box of any rectangle rotated by any angle in radians.

var newWidth= Math.Abs(height*Math.Sin(angle)) + Math.Abs(width*Math.Cos(angle))
var newHeight= Math.Abs(width*Math.Sin(angle)) + Math.Abs(height*Math.Cos(angle))

计算x和y的比例尺:

scaleX = width/newWidth;
scaleY = height/newHeight;

将其应用于您的矩形.

编辑:应用于您的示例:

    PointF center = new PointF(150, 100);
    graphics.FillRectangle(Brushes.Black, center.X, center.Y, 2, 2); // draw center point.
    var height = 200;
    var width = 300;
    var angle = 30;
    var radians = angle * Math.PI / 180;
    var boundingWidth = Math.Abs(height * Math.Sin(radians)) + Math.Abs(width * Math.Cos(radians));
    var boundingHeight = Math.Abs(width * Math.Sin(radians)) + Math.Abs(height * Math.Cos(radians));
    var scaleX = (float)(width / boundingWidth);
    var scaleY = (float)(height / boundingHeight);
    using (Matrix matrix = new Matrix())
    {
        matrix.Scale(scaleX, scaleY, MatrixOrder.Append);
        matrix.Translate(((float)boundingWidth - width) / 2, ((float)boundingHeight - height) / 2);
        matrix.RotateAt(angle, center);
        graphics.Transform = matrix;
        graphics.DrawRectangle(Pens.Black, 0, 0, width, height);
        graphics.ResetTransform();
    }

这篇关于根据用户控件旋转和缩放矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆