Paint.exe Style Zoom, NearestNeighbor Interpolation of half-pixel borders

Sorry if the title is a little cryptic. Basically I create zoom control in a C # forms application, the idea is that I can scale the image by factors, i.e. 1x, 2x, 4x, 8x. I need the image to remain pixelated, i.e. nearest neighbors. Scaling works great, except that when I select Interp for the nearest neighbors when working with border pixels, the default color is internal. This means that the outer pixels are half the width as inner pixels, where the problem really occurs when I add a tooltip to display the x, y coordinates of the current moused-over pixel that it throws off. To be clear, the reason it is discarded is because I compute the current pixel as:

void m_pictureBox_MouseMove(object sender, MouseEventArgs e) { int x = e.Location.X / m_zoomFactor; int y = e.Location.Y / m_zoomFactor; } 

and since the outer pixel is half the width ... well, you get an image.

The drawing code is simple:

 void m_pictureBox_Paint(object sender, PaintEventArgs e) { if (m_pictureBox.Image!=null) { e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; e.Graphics.ScaleTransform((float)m_zoomFactor, (float)m_zoomFactor); e.Graphics.DrawImage(m_pictureBox.Image, 0, 0); } } 

Image control is hosted in my custom ZoomControl, which itself inherits from the Panel control.

My question is basically, can any body help me solve the border pixel problem and is there a better way to get the zoom function?

+4
source share
1 answer

You also need to change Graphics.PixelOffsetMode. By default, it is None, which is suitable for interpolation, but not when you exploded pixels into blocks. Change it to half. For instance:

  public partial class Form1 : Form { public Form1() { InitializeComponent(); } private float mZoom = 10; protected override void OnPaint(PaintEventArgs e) { e.Graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half; e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; Image img = Properties.Resources.SampleImage; RectangleF rc = new RectangleF(0, 0, mZoom * img.Width, mZoom * img.Height); e.Graphics.DrawImage(img, rc); } } 
+5
source

All Articles