I try to draw some lines with different colors.
This code tries to draw two rectangles with 1px thin lines. However, the second rectangle is drawn with 2px width lines, while the first one is drawn with 1px width.
- (void)addLineFrom:(CGPoint)p1 to:(CGPoint)p2 context:(CGContextRef)context {
// set the current point
CGContextMoveToPoint(context, p1.x, p1.y);
// add a line from the current point to the wanted point
CGContextAddLineToPoint(context, p2.x, p2.y);
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGPoint from, to;
// ----- draw outer black frame (left, bottom, right) -----
CGContextBeginPath(context);
// set the color
CGFloat lineColor[4] = {26.0f * colorFactor, 26.0f * colorFactor, 26.0f * colorFactor, 1.0f};
CGContextSetStrokeColor(context, lineColor);
// left
from = CGPointZero;
to = CGPointMake(0.0f, rect.size.height);
[self addLineFrom:from to:to context:context];
// bottom
from = to;
to = CGPointMake(rect.size.width, rect.size.height);
[self addLineFrom:from to:to context:context];
// right
from = to;
to = CGPointMake(rect.size.width, 0.0f);
[self addLineFrom:from to:to context:context];
CGContextStrokePath(context);
CGContextClosePath(context);
// ----- draw the middle light gray frame (left, bottom, right) -----
CGContextSetLineWidth(context, 1.0f);
CGContextBeginPath(context);
// set the color
CGFloat lineColor2[4] = {94.0f * colorFactor, 94.0f * colorFactor, 95.0f * colorFactor, 1.0f};
CGContextSetStrokeColor(context, lineColor2);
// left
from = CGPointMake(200.0f, 1.0f);
to = CGPointMake(200.0f, rect.size.height - 2.0f);
[self addLineFrom:from to:to context:context];
// bottom
from = to;
to = CGPointMake(rect.size.width - 2.0f, rect.size.height - 2.0f);
[self addLineFrom:from to:to context:context];
// right
from = to;
to = CGPointMake(rect.size.width - 2.0f, 1.0f);
[self addLineFrom:from to:to context:context];
// top
from = to;
to = CGPointMake(1.0f, 1.0f);
[self addLineFrom:from to:to context:context];
CGContextStrokePath(context);
}
If memory serves, antialiasing is on by default which may cause more pixels to be affected by your drawing than you intend. Turn antialiasing off for your CGContextRef
and see if that helps.
iOS:
CGContextRef context = UIGraphicsGetCurrentContext();
[context setShouldAntialias:NO];
Mac:
CGContextRef context = [NSGraphicsContext currentContext];
[context setShouldAntialias:NO];