Tuesday, August 24, 2010

Circular Positioning in ASP .Net

In Puzzlepart projects several occasions I had to find a good solution for the circular positioning on html markup. There are many ways to do this and the team wanted to tryout using pure css styles that support in cross browsers.

Below sample code illustrates how to achieve this using css positing styles and the bit of mathematics. It’ll rotate the image based on selected angle.


Page View

Code:
using System;
using System.Drawing;
using System.Web.UI;

namespace RotationTest
{
    public partial class Rotation : Page
    {
        private const double Radius = 155;
        private readonly Point Origin = new Point(190, 195);

        protected string PositionStyle
        {
            get
            {
                var style = "visibility:hidden;";
                if (!string.IsNullOrEmpty(dropDownAngle.SelectedValue))
                {
                    var angle = Convert.ToDouble(dropDownAngle.SelectedValue);
                    var position = GetPointOnCircle(Origin, Radius, angle);
                    style = string.Format(
                            "left: {0}px; top: {1}px;",
                            position.X, position.Y);
                }
                return style;
            }
        }

        private static Point GetPointOnCircle(Point origin, double radius, double angleInDegrees)
        {
            // Convert from degrees to radians via multiplication by PI/180        
            var x = (int)Math.Round(radius * Math.Cos(angleInDegrees * Math.PI / 180.0), 
                                    MidpointRounding.ToEven) + origin.X;
            
            var y = (int)Math.Round(radius * Math.Sin(angleInDegrees * Math.PI / 180.0), 
                                    MidpointRounding.ToEven) + origin.Y;

            return new Point(x, y);
        }
    }
}
Markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Rotation.aspx.cs" 
    Inherits="RotationTest.Rotation" %>
<head runat="server">
    <title>Rotation Test</title>
head>
<body>
    <form id="form" runat="server">
    <div>
        <div style="width: 400px; height: 402px; background-image: url(circular-image.png);
            background-repeat: no-repeat;">            
            <img src="position-image.png" alt="position image" 
                 style="position: absolute; <%= PositionStyle %>" />                 
        </div>
        Select Angle -
        <asp:DropDownList ID="dropDownAngle" runat="server" AutoPostBack="True">
            <asp:ListItem Selected="True">0asp:ListItem>
            <asp:ListItem>60</asp:ListItem>
            <asp:ListItem>90</asp:ListItem>
            <asp:ListItem>150</asp:ListItem>
            <asp:ListItem>240</asp:ListItem>
            <asp:ListItem>320</asp:ListItem>
        asp:DropDownList>
    div>
    </form>
body>
html> 

Circular Image

Position Image

No comments: