在绘图

时间:2018-06-14 07:11:49

标签: c# gdi+ gdi graphics2d

目前我开发了一个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);
}

但问题是:当它放大时,变焦太大而且超出了我的控制范围。

有没有办法指定应该缩放(缩放)的区域?

1 个答案:

答案 0 :(得分:1)

对于最后一个问题:有没有办法指定应缩放/缩放的区域?您需要SetClipTranslateTransform和{的组合{3}}

这是一个例子。

它使用

  • 目标矩形zoomTgtArea,其中显示缩放的图形,
  • 缩放原点所在的鼠标位置zoomOrigin
  • 一个浮动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);
}

它唯一的额外是清除背景,因此正常的绘图不会通过缩放版本闪耀..

让我们看看:

ScaleTransform