Precise pixel grid overlay in Core Graphics?

In my experiments with creating a pixel-centered image editor I've been trying to draw a precise grid overlay to help guide users when trying to access certain pixels. However, the grid I draw isn't very even, especially at smaller sizes. It's a regular pattern of one slightly larger column for every few normal columns, so I think it's a rounding issue, but I can't see it in my code. Here's my code:

    - (void)drawRect:(NSRect)dirtyRect
{
    context = [[NSGraphicsContext currentContext] graphicsPort];
    CGContextAddRect(context, NSRectToCGRect(self.bounds));
    CGContextSetRGBStrokeColor(context, 1.0f, 0.0f, 0.0f, 1.0f);
    CGContextStrokePath(context);
    CGContextSetInterpolationQuality(context, kCGInterpolationNone);
    CGContextSetShouldAntialias(context, NO);

    if (image)
    {

        NSRect imageRect = NSZeroRect;
        imageRect.size = CGImageGetSize([image CGImage]);
        drawRect = [self bounds];
        NSRect viewRect = drawRect;
        CGFloat aspectRatio = imageRect.size.width / imageRect.size.height;
        if (viewRect.size.width / viewRect.size.height <= aspectRatio)
        {
            drawRect.size.width = viewRect.size.width;
            drawRect.size.height = imageRect.size.height * (viewRect.size.width / imageRect.size.width);
        }
        else
        {
            drawRect.size.height = viewRect.size.height;
            drawRect.size.width = imageRect.size.width * (viewRect.size.height / imageRect.size.height);
        }

        drawRect.origin.x += (viewRect.size.width - drawRect.size.width) / 2.0;
        drawRect.origin.y += (viewRect.size.height - drawRect.size.height) / 2.0;

        CGContextDrawImage(context, drawRect, [image CGImage]);

        if (showPixelGrid)
        {
            //Draw grid by creating start and end points for vertical and horizontal lines.
            //FIXME: Grid is uneven, especially at smaller sizes. 
            CGContextSetStrokeColorWithColor(context, CGColorGetConstantColor(kCGColorBlack));
            CGContextAddRect(context, drawRect);
            CGContextStrokePath(context);
            NSUInteger numXPoints = (NSUInteger)imageRect.size.width * 2;
            NSUInteger numYPoints = (NSUInteger)imageRect.size.height * 2;
            CGPoint xPoints[numXPoints];
            CGPoint yPoints[numYPoints];
            CGPoint startPoint;
            CGPoint endPoint;
            CGFloat widthRatio = drawRect.size.width / imageRect.size.width;
            CGFloat heightRatio = drawRect.size.height / imageRect.size.height;
            startPoint.x  = drawRect.origin.x;
            startPoint.y = drawRect.origin.y;
            endPoint.x = drawRect.origin.x;
            endPoint.y = drawRect.size.height + drawRect.origin.y;
            for (NSUInteger i = 0; i < numXPoints; i += 2)
            {
                startPoint.x += widthRatio;
                endPoint.x += widthRatio;
                xPoints[i] = startPoint;
                xPoints[i + 1] = endPoint;
            }
            startPoint.x  = drawRect.origin.x;
            startPoint.y = drawRect.origin.y;
            endPoint.x = drawRect.size.width + drawRect.origin.x;
            endPoint.y = drawRect.origin.y;
            for (NSUInteger i = 0; i < numYPoints; i += 2)
            {
                startPoint.y += heightRatio;
                endPoint.y += heightRatio;
                yPoints[i] = startPoint;
                yPoints[i + 1] = endPoint;
            }
            CGContextStrokeLineSegments(context, xPoints, numXPoints);
            CGContextStrokeLineSegments(context, yPoints, numYPoints);
        }
    }

}

Any ideas?

Answers


UPDATE: I managed to get your code running with a few tweaks - where did CGImageGetSize() come from? - and I can't really see the problem, other than columns aren't all exactly even at extremely small sizes. That's just how it has to work though. The only way around this is to either fix scaling to be integer multiples of the image size - in other words, get the largest integer multiple of the image size smaller than the view size -or reduce the number of lines drawn on the screen at very small sizes to get rid of this artefact. There's a reason the pixel grid only becomes visible when you zoom in a long way in most editors. Not to mention that if the grid is still visible at 3-4x resolution you're making the view just way too busy.


I couldn't run the code you provided because there's a bunch of class ivars in there, but from a cursory glance, I'd say it has something to do with drawing on pixel boundaries. After you round to an integer to get rid of fuzzy AA artefacts (I notice you turned AA off, but ideally you shouldn't have to do that), you then need to add 0.5 to your origin to get your line drawn in the center of the pixel rather than on the boundary.

Like this:

+---X---+---+---+---+---+
|   |   |   | Y |   |   |
+---+---+---+---+---+---+

X : CGPoint (1, 1)
Y : CGPoint (3.5, 0.5)

You want to draw from the center of the pixel, because otherwise your line straddles two pixels.

In other words, where you're setting up xPoints and yPoints, make sure to floor() or round() your values, and then add 0.5.


Need Your Help

Eclipse bug with nine patch files?

android eclipse resources nine-patch

I tried to convert all my buttons background to .9.png, but I have a problem with Eclipse.

Dalvik VM error: Exception found “Javax.xml.namespace.QName.class”

java android eclipse dalvik google-places-api

This isn't intended to be a question. Rather, an observation which is a common problem found in Android when you use external APIs for development and android.jar isn't duplicated into your project!

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.