Reference
[1] https://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/CGContext/Reference/reference.html
[2] https://developer.mozilla.org/en-US/docs/HTML/Canvas/Tutorial/Applying_styles_and_colors? Redirectlocale = en-US & redirectslug = canvas_tutorial % 2fapplying_styles_and_colors # a_linewidth_example
In drawrect, two horizontal lines can be drawn using the following code. The line width is 1 pixel, and cgcontextsetlinewidth (contextref, 1) is used. The line width is set to 1 pixel.
CGContextRef contextRef = UIGraphicsGetCurrentContext();CGContextSetStrokeColorWithColor(contextRef, [UIColor redColor].CGColor);CGContextSetLineWidth(contextRef, 1);CGContextMoveToPoint(contextRef, 10, 20);CGContextAddLineToPoint(contextRef, 180, 20);CGContextStrokePath(contextRef);CGContextMoveToPoint(contextRef, 10, 40.5);CGContextAddLineToPoint(contextRef, 180, 40.5);CGContextStrokePath(contextRef);
The display effect is as follows. We can see that the line below is bright and the line above is blurred. Why ?!
In reference 1, The cgcontextsetlinewidth method is described as follows: if the width is set to a line of 1 pixel, the drawn lines are on both sides of the painted path, and each side is half the width, that is, 0.5 pixels.
Or the so-called line width refers to the width from the center of the given path to both sides. In other words, the width is drawn half of each side of the path.
The default line width is1Unit. When Stroked, the line straddles the path, with half of the total width on either side.
While the image is being drawn on the screen, the image is drawn in pixels. If the display content is less than one pixel, the image is used by default for smooth display. As shown in the middle figure below, for a blue line with a pixel width, there are about 0.5 pixels, and the remaining 0.5 pixels are anti-sawtooth and drawn in light blue.
To avoid this problem, you can use either of the following methods:
1. line width is taken into account during painting, and width is evenly distributed to both sides when path is set. For example, when the red line below is drawn, 0.5 pixels are offset to y direction, cgcontextmovetopoint (contextref,
10, 40.5); cgcontextaddlinetopoint (contextref, 180, 40.5); details are shown later in.
2. cgcontextsetallowsantialiasing (contextref, no.
After method 2 is used, the effect is as follows. It can be seen that the upper and lower straight lines have the same effect.