Skip to content

Instantly share code, notes, and snippets.

@hpux735
Created February 27, 2012 23:14
Show Gist options
  • Save hpux735/1927842 to your computer and use it in GitHub Desktop.
Save hpux735/1927842 to your computer and use it in GitHub Desktop.
Pixel aligning lines using Quartz (from the TreeView sample code)
// Compute the needed adjustment in x and y to align our lines for crisp, exact pixel coverage. (We can only do this if the lineWidth is integral, which it usually is.)
CGFloat adjustment = 0.0;
CGFloat lineWidth = [[self enclosingTreeView] connectingLineWidth];
NSSize lineSize = NSMakeSize(lineWidth, lineWidth);
NSSize lineSizeInPixels = [self convertSizeToBase:lineSize];
CGFloat halfLineWidthInPixels = 0.5 * lineSizeInPixels.width;
if (fabs(halfLineWidthInPixels - floor(halfLineWidthInPixels)) > 0.0001) {
// If line width in pixels is odd, lay our path segments along the centers of pixel rows.
NSSize adjustmentAsSizeInPixels = NSMakeSize(0.5, 0.5);
NSSize adjustmentAsSize = [self convertSizeFromBase:adjustmentAsSizeInPixels];
adjustment = adjustmentAsSize.width;
}
NSRect bounds = [self bounds];
NSPoint basePoint;
// Compute point at right edge of root node, from which its connecting line to the vertical line will emerge.
NSPoint rootPoint = NSMakePoint(NSMinX(bounds), NSMidY(bounds));
// Align the line to get exact pixel coverage, for sharper rendering.
basePoint = [self convertPointToBase:rootPoint];
basePoint.x = round(basePoint.x) + adjustment;
basePoint.y = round(basePoint.y) + adjustment;
rootPoint = [self convertPointFromBase:basePoint];
// Compute point (really, we're just interested in the x value) at which line from root node intersects the vertical connecting line.
NSPoint rootIntersection = NSMakePoint(NSMidX(bounds), NSMidY(bounds));
// Align the line to get exact pixel coverage, for sharper rendering.
basePoint = [self convertPointToBase:rootIntersection];
basePoint.x = round(basePoint.x) + adjustment;
basePoint.y = round(basePoint.y) + adjustment;
rootIntersection = [self convertPointFromBase:basePoint];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment