Rotate graphic towards mouse in WPF (like an analog dial)

后端 未结 3 1379
臣服心动
臣服心动 2020-12-29 14:48

In WPF/C# how would I rotate a \"graphic\" to face the current mouse position?

Basically what I want is a \"wheel\" UI Control (like an analog volume dial

3条回答
  •  感情败类
    2020-12-29 15:34

    In my case i have dynamically created shapes which shall rotated toward mouse direction. To solve this I used a lightweight function. All I need is following:

    • The centerpoint of the current selected shape
    • The point from the last mouseover step
    • And the point from the current mouseover step

    It is not necessary to use methods from the Math library. I calculate the angle which depends on the difference of the current mouse over point and the previous mouse over point and the position in relation o the center point. Finally I add the angle on the exisitng angle of the current object.

    private void HandleLeftMouseDown(MouseButtonEventArgs eventargs)
    {
        //Calculate the center point of selected object
        //...
        //assuming Point1 is the top left point
        var xCenter = (_selectedObject.Point2.X - _selectedObject.Point1.X) / 2 + _selectedObject.Point1.X
        var yCenter = (_selectedObject.Point2.Y - _selectedObject.Point1.Y) / 2 + _selectedObject.Point1.Y
        _selectedObjectCenterPoint = new Point((double) xCenter, (double) yCenter);
    
        //init set of last mouse over step with the mouse click point
         var clickPoint = eventargs.GetPosition(source);
        _lastMouseOverPoint = new Point(clickPoint.X,clickPoint.Y);
    }
    
    private void HandleMouseMove(MouseEventArgs eventArgs)
    {
        Point pointMouseOver = eventArgs.GetPosition(_source);                            
    
        //Get the difference to the last mouse over point
        var xd = pointMouseOver.X - _lastMouseOverPoint.X;
        var yd = pointMouseOver.Y - _lastMouseOverPoint.Y;
    
        // the direction depends on the current mouse over position in relation to the center point of the shape
        if (pointMouseOver.X < _selectedObjectCenterPoint.X)
            yd *= -1;
        if (pointMouseOver.Y > _selectedObjectCenterPoint.Y)
            xd *= -1;
    
        //add to the existing Angle   
        //not necessary to calculate the degree measure
        _selectedObject.Angle += (xd + yd);
    
        //save mouse over point            
        _lastMouseOverPoint = new Point(pointMouseOver.X, pointMouseOver.Y);
    }
    

提交回复
热议问题