winforms 缩放和滚动图像

xt0899hw  于 2023-04-21  发布在  其他
关注(0)|答案(1)|浏览(98)

在我的on paint事件中,我试图保持图像居中,但也允许用户通过滚动来放大照片。当滚动轮显示时,图像似乎偏离了一点,并在屏幕上绘制切断图像任何人都可以帮助?

protected override void OnPaint(PaintEventArgs e)
{
    if (_image == null)
    {
       base.OnPaintBackground(e);
       return;
    }
    Rectangle rect = this.DisplayRectangle;

    // Get a gradient brush and fill the background. 
    Brush backBrush =  new SolidBrush(Color.Gray);
    e.Graphics.FillRectangle(backBrush, rect);
    int x = (this.Width - (int)(_image.Width * _zoom)) / 2;
    int y = (this.Height - (int)(_image.Height * _zoom)) / 2;
    // Calculate the panning amount to keep the image centered
    Matrix mx = new Matrix(_zoom, 0, 0, _zoom, x, y);
    mx.Translate(this.AutoScrollPosition.X / _zoom - x, this.AutoScrollPosition.Y / _zoom- y);
    e.Graphics.Transform = mx;
    e.Graphics.InterpolationMode = _interpolationMode;
    // Calculate the top-left corner of the image
    
    e.Graphics.DrawImage(_image, new Rectangle(x, y, this._image.Width, this._image.Height), 0, 0, _image.Width, _image.Height, GraphicsUnit.Pixel);

    base.OnPaint(e);
}
qyuhtwio

qyuhtwio1#

我修好了

// Get a gradient brush and fill the background. 
        Brush backBrush =  new SolidBrush( Color.Gray);
        e.Graphics.FillRectangle(backBrush, rect);
       
        int x = (this.Width - (int)(_image.Width * _zoom)) / 2;
        int y = (this.Height - (int)(_image.Height * _zoom)) / 2;
        if (this.HScroll)
            x = 0;
        if (this.VScroll)
            y = 0;
        // Calculate the panning amount to keep the image centered
        Matrix mx = new Matrix(_zoom, 0, 0, _zoom, x, y);
        mx.Translate(this.AutoScrollPosition.X / _zoom - x, this.AutoScrollPosition.Y / _zoom- y);
        e.Graphics.Transform = mx;
        e.Graphics.InterpolationMode = _interpolationMode;
        // Calculate the top-left corner of the image
        
        e.Graphics.DrawImage(_image, new Rectangle(x, y, this._image.Width, this._image.Height), 0, 0, _image.Width, _image.Height, GraphicsUnit.Pixel);`

相关问题