Canvas graphics move, scale code in WPF

Source: Internet
Author: User

From Flash to C #, a lot of content smattering, while groping side forward, code rough, right when leaving a footprint.

Just want a basic mobile and zoom function interface, looking for a long time are drawing lines, draw rectangles and other basic shape of the code, moving and scaling is not clear, can only work to solve.

Material Preparation:

A canvas control, named CANVAS1, is placed on the screen of a WPF project.

The code is as follows:

1 usingSystem;2 usingSystem.Windows;3 usingSystem.Windows.Media;4 usingSystem.Windows.Input;5 usingSystem.Windows.Shapes;6 usingSystem.Windows.Controls;7 8 namespacewpfcanvasdrawing9 {Ten     /// <summary> One     ///the interactive logic of MainWindow.xaml A     /// </summary> -      Public Partial classMainwindow:window -     { the         //Move Flag -         BOOLIsmoving =false; -         //where the mouse is pressed down - Point startmoveposition; +  -TranslateTransform totaltranslate =NewTranslateTransform (); +TranslateTransform temptranslate =NewTranslateTransform (); AScaleTransform Totalscale =NewScaleTransform (); atDouble Scalelevel =1; -  -          PublicMainWindow () -         { - InitializeComponent (); -  inCANVAS1. Focusable =true;//Important: Mouse events are not received by default -  toDrawingline (NewPoint ( -, -),NewPoint ( -, $)); +Drawingline (NewPoint ( -, $),NewPoint ( -, -)); -         } the  *         Private voidWindow_sizechanged (Objectsender, Sizechangedeventargs e) $         {Panax Notoginseng             //Issue One: Failed to change canvas size when clicking the window Maximize button -             //if (this. WindowState = = windowstate.maximized) {} theCANVAS1. Width = This. Width; +CANVAS1. Height = This.  Height;  A            the         } +  -         protected voidDrawingline (Point startpt, point endpt) $         { $LineGeometry Mylinegeometry =Newlinegeometry (); -Mylinegeometry.startpoint =startpt; -Mylinegeometry.endpoint =ENDPT; the  -Path MyPath =NewPath ();WuyiMypath.stroke =Brushes.black; theMypath.strokethickness =1; -Mypath.data =Mylinegeometry; Wu  - CANVAS1. Children.add (MyPath); About         } $  -         Private voidCanvas1_mouseleftbuttondown (Objectsender, MouseButtonEventArgs e) -         { -             //Code A: A             //FrameworkElement element = sender as FrameworkElement; +             //startmoveposition = e.getposition (element); the             //Code B: -Startmoveposition =e.getposition ((Canvas) sender); $Ismoving =true; the         } the  the         Private voidCanvas1_mouseleftbuttonup (Objectsender, MouseButtonEventArgs e) the         { -Ismoving =false; inPoint endmoveposition =e.getposition ((Canvas) sender); the  the             //In order to avoid jumping-type transformation, a single effective change tired join totaltranslate.  AboutTotaltranslate.x + = (endmoveposition.x-startmoveposition.x)/Scalelevel; theTotaltranslate.y + = (ENDMOVEPOSITION.Y-STARTMOVEPOSITION.Y)/Scalelevel;  the         } the  +         Private voidCanvas1_mousemove (Objectsender, MouseEventArgs e) -         { the             if(ismoving)Bayi             { thePoint currentmouseposition = E.getposition ((Canvas) sender);//Current mouse position the                  -Point deltapt =NewPoint (0,0);  -Deltapt.x = (currentmouseposition.x-startmoveposition.x)/Scalelevel;  theDeltapt.y = (CURRENTMOUSEPOSITION.Y-STARTMOVEPOSITION.Y)/Scalelevel; the                  thetemptranslate.x = totaltranslate.x +Deltapt.x; theTemptranslate.y = Totaltranslate.y +Deltapt.y; -  the adjustgraph (); the             } the         }        94          the         Private voidCanvas1_mousewheel (Objectsender, MouseWheelEventArgs e) the         { thePoint ScaleCenter =e.getposition ((Canvas) sender);98  About             if(E.delta >0) -             {101Scalelevel *=1.08;102             }103             Else104             { theScalelevel/=1.08;106             }107             //Console.WriteLine ("Scalelevel: {0}", scalelevel);108 109Totalscale.scalex =Scalelevel; theTotalscale.scaley =Scalelevel;111Totalscale.centerx =scalecenter.x; theTotalscale.centery =scalecenter.y;113  the adjustgraph (); the         } the        117         Private voidadjustgraph ()118         {119TransformGroup Tfgroup =NewTransformGroup (); - TfGroup.Children.Add (temptranslate);121 TfGroup.Children.Add (Totalscale);122 123             foreach(UIElement UEinchCANVAS1. Children)124             { theUe. RenderTransform =Tfgroup;126             }127         } - 129     } the}

Variable Description:

// move flag bool ismoving = false<        Span style= "COLOR: #000000" >; // mouse down position  point Startmoveposition; TranslateTransform totaltranslate = new TranslateTransform ();//The total amount of movement needs to be counted in multiple operations. TranslateTransform temptranslate = new TranslateTransform ();//The mouse position is updated in real-time during a single move. ScaleTransform Totalscale = new ScaleTransform ();//scale variable Double scalelevel = 1;//zoom level 

function Description:
drawingline draw a line in the specified canvas control for testing.
 When the mouse is pressed, the position where the start movement is recorded, Marks the start of the drag operation ismoving = True.  

When the mouse is lifted, the valid move distance is recorded to the total move variable totaltranslate.
Adjust the wheel orientation as the mouse wheel changes
The zoom level.

at different zoom levels, the screen moves the same distance, which is different from the graphics within the Canvs, so you need to fix the distance of the mouse movement, dividing the moving distance by the zoom level, This gives you a relatively precise moving position.

legacy:
1, after scaling, there will still be a small jitter, There are also flaws in the details processing.
2, window maximization button Click, can not capture related events, resulting in canvas1 can not be magnified at the same time, please help the Expert to guide you, thank you!

Canvas graphics move, scale code in WPF

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.