Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

winforms graphics with nearest neighbor filtering clipping edges of image

I'm writing a Chip8 emulator/interpreter. It's going great. To the point I need a UI to play some games and watch this bad Jackson in motion. I first ran into a problem where drawing the framebuffer (which is just a bitmap) to the screen was super-blurry. After figuring out I needed to set the interpolation mode to Nearest Neighbor it looked much better, but it seems the edges of the image are either being clipped or I'm misunderstanding the interpolation at work. Here's a screenshot.

A screenshot of the issue.  Note the edges.

The edges you see around the top, left, and right should end with "whole" white pixels keeping with the pattern you see. Especially easy to see the issue at the top left, should be one whole white pixel.

The image being upscaled is 64x32, and is being drawn using a normal graphics object, as such: (ignore the 64 * 6, I know it's funny)

g.DrawImage (cpu.raster, 0, 0, 64 * 6, 32 * 6);

Where "cpu.raster" is the bitmap the emulator renders the game to. I'd post the rest of the code, but it all seems pretty standard. The only other code that even relates to the graphics is the interpolation/smoothing modes, which are set as such:

        g = this.CreateGraphics ();
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
        this.DoubleBuffered = true;

Is there another setting I should be aware of to prevent this? I tried reducing the size of the drawn image, thinking maybe the form was clipping it somehow, but it's not, the image ends at the edges you see in the screenshot.

like image 344
ALLCAPS Avatar asked Jan 20 '14 21:01

ALLCAPS


1 Answers

In the code where you are setting InterpolationMode and SmoothingMode, add this line:

g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;

That will fix the top and left sides of what you are drawing. As for the right side, make sure your form is wide enough to accomodate the image. The width you specify is 64 * 6 = 384, but in the screenshot it appears your form has 377 pixels of display area.

like image 144
endofzero Avatar answered Nov 13 '22 17:11

endofzero