如何计算旋转图像的正确位置偏移

How to calculate correct position offsets for rotated image?

本文关键字:位置 图像 旋转 何计算 计算      更新时间:2023-09-26

我正在尝试创建一个小仪表控件,有点像汽车中的速度表,只是它只跨越180度。

为了渲染控件,我使用了两个图像文件。第一个只是仪表的背景,显示了一个从0度的绿色到180度的红色的半圆。第二个图像是一个垂直箭头,其高度与半圆的半径大致相同,但略小于背景图像的高度。

我正在使用以下标记来呈现控件:

<div class="gauge" id="@Model.ClientID">
    <img class="gauge" alt="" src="@Url.Content( "~/images/icons/gauge-bg.png" )" />
    <img class="arrow" alt="" src="@Url.Content( "~/images/icons/gauge-arrow.png" )" />
</div>

图像相对地位于div内部,以允许它们重叠。背景图像为120x63像素,箭头图像为12x58像素(WxH),但如果可以更容易地解决问题,则可以进行调整。在应用任何旋转之前,箭头图像指向正上方。

我有一个百分比(从0到100),我将其转化为箭头图像的旋转角度(从-90到90),看起来像这样:

// input value for the offset calculations (see below)
public double ArrowRotationDegrees 
{
    // 0 for 0%, 90 for 50% and 180 for 100%
    get { return 180.0 * Percent / 100; }
}
// input value for the jquery rotate plugin as our base arrow points vertically up
public double ArrowRotationDegreesRelative // -90 for 0%, 0 for 50% and 90 for 100%
{
    // -90 for 0%, 0 for 50% and 90 for 100%
    get { return ArrowRotationDegrees - 90; }
}

为了执行旋转,我使用jquery rotate,它似乎总是围绕图像的中心旋转。

<script type="text/javascript">
    $(document).ready(function () {
        var arrow = $('#@Model.ClientID').find('img.arrow');
        arrow.rotate(@Model.ArrowRotationDegreesRelative);
        arrow.css({left: @Model.ArrowLeftShiftPixels, top: @Model.ArrowTopShiftPixels});
    });
</script>

但是,如何计算重新定位旋转图像的正确偏移量,使箭头始终指向背景图像的确切中心底部?

更新-解决方案

根据Eric J.的回答,我可以在不更改标记的情况下调整代码并获得工作结果:

public int ArrowLeftShiftPixels // used to position rotated image correctly horizontally
{
    // default offset (no rotation) is left:55
    get { return 55 - GetArrowLeftShift( ArrowRotationDegrees ); }
}
public int ArrowTopShiftPixels // used to position rotated image correctly vertically
{
    // default offset (no rotation) is top:5
    // formula output is shifted (max appears where min should be); add 29 to reverse this effect
    get { return 34 - GetArrowTopShift( ArrowRotationDegrees ); }
}
public int GetArrowLeftShift( double degrees )
{
    var result = (58.0 / 2) * Math.Cos( degrees * Math.PI / 180 );
    return (int) Math.Round( result, 0 );
}
public int GetArrowTopShift( double degrees )
{
    var result = (58.0 / 2) * Math.Sin( degrees * Math.PI / 180 );
    return (int) Math.Round( result, 0 );
}

感谢您的帮助和建议!

我没有详细查看问题的具体数字(底部的箭头是向上的还是相反?),但您可能会发现箭头的尖端在图像中心的左右移动了(half it's length) * cos(Angle),而在向上或向下移动了(half it's length) * sin (Angle)。在指定角度时,请确保使用弧度或度数来计算sin和cos。

如果在C#中计算服务器端的sin和cos,请使用弧度。

这里有一个关于如何旋转任意角度的解释(与我刚才解释的一致,但图表可能会有所帮助)。请注意,在您的情况下,初始角度为0,因此初始公式为

x=0(由于cos(0)=0)y=r(由于r*sin(0)=r)

您可以在两个维度上生成一个大约是图像大小两倍的div。然后你可以把你的图像放在这个div里面,所以图像的轴心点(箭头的底部)在div的一半高和一半宽。然后将div转换到正确的区域(这样图像的关键点就在正确的区域),然后对div执行旋转。

编辑:这是一个解释http://jsfiddle.net/pVpE7/

看看这个例子。说明:

rotate插件不允许您指定锚点——它总是围绕中心旋转。我只是把箭头的大小增加了一倍,这样它就可以延伸到仪表的宽度上。旋转此箭头可以获得所需的效果。对CSS添加了一些小的调整,以控制箭头的溢出部分。