【发布时间】:2012-03-31 04:13:31
【问题描述】:
我正在尝试创建一个小型仪表控制,有点像汽车中的速度计,只是它只跨越 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 );
}
感谢所有帮助和建议!
【问题讨论】:
标签: c# javascript css math