UIView drawRect draw lines of irregular width

I am trying to add a small red line at the bottom of my UIView.

I want the string to be a 1px string.

Can someone tell me why the following code:

- (void)drawRect:(CGRect)rect { CGContextRef currentContext = UIGraphicsGetCurrentContext(); CGContextSaveGState(currentContext); CGContextSetRGBFillColor(currentContext, 0.0f, 0.0f, 0.0f, 1.0f); CGContextFillRect(currentContext, RECT(0, 0, rect.size.width, rect.size.height - 8)); CGContextSetLineWidth(currentContext, 1); CGContextSetRGBStrokeColor(currentContext, 1.0f, 0.0f, 0.0f, 1.0f); CGContextBeginPath(currentContext); CGContextMoveToPoint(currentContext, 0, rect.size.height - 7); CGContextAddLineToPoint(currentContext, rect.size.width, rect.size.height - 7); CGContextStrokePath(currentContext); CGContextRestoreGState(currentContext); } 

Draws a line that is 2px high?

+4
source share
3 answers

Integral coordinates indicate halfway between pixels; that is, (0,0) is in the upper left corner, above and to the left of the upper left pixel; likewise, (1,0) is between the first and second pixels; finally (0.5.0.5) is in the center of the upper left pixel.

According to the documentation for CGContextSetLineWidth , "when stroking, the line crosses the path with half the total width on both sides." Thus, if the path lies exactly between the pixels, the line will be smoothed half by one row of pixels, half by another.

Therefore, to get the exact pixel line, you must shift your coordinates by half a pixel: for your x coordinate, use rect.size.height - 7.5 instead of - 7 .

By the way, when drawing rectangles it is convenient to use CGRectInset(rect, 0.5, 0.5) to achieve this.

+13
source

Are you using an iPhone 4? The iPhone 4 uses a coordinate system with a scale factor of 2. Therefore, you need to set the line width to 0.5 to get what you want.

(The coordinate system is configured so that the same code produces the same output for all models.)

+1
source

Lines are processed by default by anti-aliasing (unless you have configured otherwise). Thus, any line that is not strictly vertical or horizontal and starts and ends on a pixel probably partially covers several pixels in some rows and / or columns, which makes it a wider gray line instead of a thin high-contrast line.

0
source

All Articles