2011-02-23 42 views
2

我正在處理與頻率爲M重複的數據(像正弦/餘弦波等東西)。我已經寫了一個簡單的顯示控件,它將數據和繪製連接的線條繪製成代表數據的數據一張漂亮的照片。圖形轉換

我的問題是,如果在位圖上繪製數據,那麼象限1數據位於象限3,而象限2數據位於象限4(反之亦然)。

位圖的寬度爲M,高度爲array.Max - array.Min

是否有一個簡單的變換來更改數據,以便它顯示在適當的象限中?

回答

3

思考它的一個好方法是,(0,0)在世界上,而(寬度/ 2,高度/ 2)的圖像座標之間

(0,0), (width, 0), (0,height), (width, height)

座標被劃分。

從那裏,改造將是:

Data(x,y) => x = ABS(x - (width/2)), y = ABS(y - (Height/2)) 
2

嘗試使用反轉

g.ScaleTransform(1, -1); 
+0

我不熟悉ScaleTransform。我會研究它。如果我能把你擡高,我會!但我需要x和y軸。 Joe在解釋它的時候做得比我更好 – 2011-02-23 22:45:02

3

Graphics.ScaleTransform是不是一個好主意y軸,因爲它不僅會影響佈局,但也繪製自己(筆劃厚度,文字等)。

我建議你準備點列表,然後使用Matrix類對它們進行轉換。這是我爲你做的一個小例子,希望它會有所幫助。

private PointF[] sourcePoints = GenerateFunctionPoints(); 

    protected override void OnPaint(PaintEventArgs e) 
    { 
     base.OnPaint(e); 

     e.Graphics.Clear(Color.Black); 

     // Wee need to perform transformation on a copy of a points array. 
     PointF[] points = (PointF[])sourcePoints.Clone(); 

     // The way to calculate width and height of our drawing. 
     // Of course this operation may be performed outside this method for better performance. 
     float drawingWidth = points.Max(p => p.X) - points.Min(p => p.X); 
     float drawingHeight = points.Max(p => p.Y) - points.Min(p => p.Y); 

     // Calculate the scale aspect we need to apply to points. 
     float scaleAspect = Math.Min(ClientSize.Width/drawingWidth, ClientSize.Height/drawingHeight); 

     // This matrix transofrmation allow us to scale and translate points so the (0,0) point will be 
     // in the center of the screen. X and Y axis will be scaled to fit the drawing on the screen. 
     // Also the Y axis will be inverted. 
     Matrix matrix = new Matrix(); 
     matrix.Scale(scaleAspect, -scaleAspect); 
     matrix.Translate(drawingWidth/2, -drawingHeight/2); 

     // Perform a transformation and draw curve using out points. 
     matrix.TransformPoints(points); 
     e.Graphics.DrawCurve(Pens.Green, points); 
    } 

    private static PointF[] GenerateFunctionPoints() 
    { 
     List<PointF> result = new List<PointF>(); 

     for (double x = -Math.PI; x < Math.PI; x = x + 0.1) 
     { 
      double y = Math.Sin(x); 
      result.Add(new PointF((float)x, (float)y)); 
     } 

     return result.ToArray(); 
    } 

    protected override void OnSizeChanged(EventArgs e) 
    { 
     base.OnSizeChanged(e); 
     Invalidate(); 
    } 
+0

謝謝,你在哪裏找到Matrix數據集? – 2011-02-23 23:14:51

+0

對不起,我忘了提及,你需要導入命名空間System.Drawing.Drawing2D – 2011-02-23 23:51:54

1

還記得在縮放背景圖,如果你要,筆例如發生在一些構造的寬度爲單身,意味着成反比的分數值可以被用來製造的一個不變的補償ScaleTransform的效果。

更新:忘記,Pen有它自己的本地ScaleTransform,所以x和y都可以得到補償。