xx.xmal.cs 後臺代碼中動態添加控件到 UI
文字顯示在一個 Canvas 中(定位用Canvas.SetLeft() / Canvas.SetTop() ), 爲了實現排版效果,可適當在 TextBlock 外套一層 StackPanel 或 DockPanelide
DockPanel pnl = new DockPanel(); TextBlock titleBlock = new TextBlock(); titleBlock.LayoutTransform = new RotateTransform() { Angle = 270 // or 90 }; titleBlock.VerticalAlignment = VerticalAlignment.Center; titleBlock.Text = "Here some Text"; Canvas.SetLeft(pnl, 50); Canvas.SetTop(pnl, 100);
這時候,文本旋轉,跟定位時的 座標 X Y 並無相互影響(也就是上面的設位置,不須要做什麼特別考慮)。 而另外一種狀況:spa
在渲染過程當中自定義渲染內容 ( 重寫的 OnRender )
// Sample -- Ctrl => Height:500 Width:600 protected override void OnRender(DrawingContext dc) { base.OnRender(dc); // TODO : for sample var CtrlWidth = 600; var CtrlHeight = 400; // ... // DrawTitle var ft = new FormattedText("Some Text Here", CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Tahoma"), 15, Brushes.Black); // use ft.Width and ft.Height to calculate POSITIONS RotateTransform RT = new RotateTransform() { Angle = 270 }; // 要旋轉的角度 var point = new Point((CtrlHeight - ft.Width) / 2 - CtrlWidth, (CtrlWidth - ft.Height)/2 - CtrlHeight); // 注意這裏的計算 很容易迷糊 dc.PushTransform(RT); dc.DrawText(ft, point ); dc.Pop(); // Do other Drawing.. }
要點:
OnRender 中旋轉時,以渲染對象的 Point(0, 0) 點爲基準,進行旋轉,270度,90度的時候,就是X Y對調的狀況。
當旋轉180度的時候,X取反,Y取反。code