簡體   English   中英

在圖形上使用graphics.ScaleTransform

[英]Use graphics.ScaleTransform on Drawing

目前,我開發了一個ChartControl,並且在我看來它可以很好地工作,但是現在我處於能夠縮放繪制的信號以進行更好的分析的能力的位置。

目前,我這樣計算所需的點:

for (int i = 0; i < PointsCount; i++){
    xAxisPoint = xAxisOP.X + i * (xAxisWidth / PointsCount);
    yAxisPoint = yAxisHeight * data[i].Point / Divisor;

    if(yAxisPoint > yAxisHeight){
        yAxisPoint = yAxisHeight;  
    }

    if(yAxisPoint < -yAxisHeight){
        yAxisPoint = -yAxisHeight;
    }

    Points[i] = new PointF(xAxisPoint, yAxisOP.Y + yAxisPoint);
}

if(zoom){
    graphics.ScaleTransform(0.2f*ZoomFactor, 0.2f*ZoomFactor);
}

using (Pen plotPen = new Pen(plotColor, 1)){
    graphics.DrawLines(plotPen, Points);
}

但是問題是:放大時,縮放太大,並超出了控件的范圍。

有沒有辦法指定應該縮放(縮放)的區域?

對於最后一個問題: 是否有一種方法可以指定應該縮放/縮放的區域? 你需要的組合SetClipTranslateTransformScaleTransform

這是一個例子。

它使用

  • 顯示放大的圖形的目標矩形zoomTgtArea
  • 鼠標位置zoomOrigin縮放原點所在的位置
  • 一個float zoomFactor ,一個正float

初始值:

Rectangle zoomTgtArea = new Rectangle(300, 500, 200, 200);
Point zoomOrigin = Point.Empty;   // updated in MouseMove when button is pressed
float zoomFactor = 2f;

僅放大一部分圖形的技巧是將圖形顯示兩次 ,一次正常顯示一次,一次通過Graphics對象的轉換一次顯示。

我們試試吧:

private void pictureBox_Paint(object sender, PaintEventArgs e)
{
    // normal drawing
    DrawStuff(e.Graphics);

    // for the movable zoom we want a small correction
    Rectangle cr = pictureBox.ClientRectangle;
    float pcw =  cr.Width / (cr.Width - ZoomTgtArea.Width / 2f) ;
    float pch =  cr.Height / (cr.Height - ZoomTgtArea.Height / 2f) ;

    // now we prepare the graphics object; note: order matters!
    e.Graphics.SetClip(zoomTgtArea );
     // we can either follow the mouse or keep the output area fixed:
    if (cbx_fixed.Checked)
        e.Graphics.TranslateTransform( ZoomTgtArea.X -  zoomCenter.X * zoomFactor,
                                        ZoomTgtArea.Y -  zoomCenter.Y * zoomFactor);
    else
        e.Graphics.TranslateTransform(  - zoomCenter.X * zoomFactor * pcw,
                                        - zoomCenter.Y * zoomFactor * pch);
    // finally zoom
    e.Graphics.ScaleTransform(zoomFactor, zoomFactor);

    // and display zoomed
    DrawStuff(e.Graphics);
}

我使用的DrawStuff很簡單:

void DrawStuff(Graphics g)
{
    bool isZoomed = g.Transform.Elements[0]!= 1   
                ||  g.Transform.OffsetX != 0 | g.Transform.OffsetY != 0;
    if (isZoomed) g.Clear(Color.Gainsboro);   // pick your back color

    // all your drawing here!
    Rectangle r =  new Rectangle(10, 10, 500, 800);  // some size
    using (Font f = new Font("Tahoma", 11f))
        g.DrawString(text, f, Brushes.DarkSlateBlue, r);
}

唯一的好處是清除背景,這樣正常的圖形就不會在縮放版本中發光。

讓我們來看看:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM