pictureBox zoom onpaint仅适用于矩形

时间:2019-05-11 15:57:55

标签: c#

我正在尝试了解复杂的GDI模块。

下面,我有一些代码允许用户在pictureBox上进行放大和缩小,但它仅对矩形执行。仅当鼠标悬停在GDI绘制的小矩形上时才有效。您如何向我展示如何将此效果应用于pictureBox中加载的实际图像?这些图像的分辨率高达7200 x 4800。

这是代码。

private Matrix transform = new Matrix();
private float m_dZoomscale = 1.0f;
public const float s_dScrollValue = 0.1f;

public Form1()
{
    InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
    Image image;

    // open file dialog
    OpenFileDialog open = new OpenFileDialog();
    // image filters
    open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp; *.tiff)|*.jpg; *.jpeg; *.gif; *.bmp; *.tiff";
    if (open.ShowDialog() == DialogResult.OK)
    {
        image = Image.FromFile(open.FileName);
        pictureBox1.Height = image.Height;
        pictureBox1.Width = image.Width;
        pictureBox1.Image = image;
    }
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;
    g.Transform = transform;
    Pen mypen = new Pen(Color.Red, 5);
    Rectangle rect = new Rectangle(10, 10, 30, 30);
    e.Graphics.DrawRectangle(mypen, rect);
}

protected override void OnMouseWheel(MouseEventArgs mea)
{
    pictureBox1.Focus();
    if (pictureBox1.Focused == true && mea.Delta != 0)
    {
        // Map the Form-centric mouse location to the PictureBox client coordinate system
        Point pictureBoxPoint = pictureBox1.PointToClient(this.PointToScreen(mea.Location));
        ZoomScroll(pictureBoxPoint, mea.Delta > 0);
    }
}

private void ZoomScroll(Point location, bool zoomIn)
{
    // Figure out what the new scale will be. Ensure the scale factor remains between
    // 1% and 1000%
    float newScale = Math.Min(Math.Max(m_dZoomscale + (zoomIn ? s_dScrollValue : -s_dScrollValue), 0.1f), 10);

    if (newScale != m_dZoomscale)
    {
        float adjust = newScale / m_dZoomscale;
        m_dZoomscale = newScale;

        // Translate mouse point to origin
        transform.Translate(-location.X, -location.Y, MatrixOrder.Append);

        // Scale view
        transform.Scale(adjust, adjust, MatrixOrder.Append);

        // Translate origin back to original mouse point.
        transform.Translate(location.X, location.Y, MatrixOrder.Append);

        pictureBox1.Invalidate();
    }
}

0 个答案:

没有答案