Smoothing a rounded stroke in Core Graphics

I create my own UITableViewCells with gradient background. I have all the logic and the drawing, but the one thing I want to fix is ​​the "chunkiness" around the corners of my custom cell:

alt text http://grab.by/27SM

If you approach in the corners, you can see what I'm talking about. Here is the code I use to create the cell:

CGContextRef c = UIGraphicsGetCurrentContext(); CGColorSpaceRef myColorspace = CGColorSpaceCreateDeviceRGB(); CGGradientRef myGradient = nil; CGFloat components[8] = TABLE_CELL_BACKGROUND; CGContextSetStrokeColorWithColor(c, [[UAColor colorWithWhite:0.7 alpha:1] CGColor]); CGContextSetLineWidth(c, 2); CGContextSetAllowsAntialiasing(c, YES); CGContextSetShouldAntialias(c, YES); CGFloat minx = CGRectGetMinX(rect) , midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect) ; CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ; CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, minx, miny); CGPathAddArcToPoint(path, NULL, minx, maxy, midx, maxy, kDefaultMargin); CGPathAddArcToPoint(path, NULL, maxx, maxy, maxx, miny, kDefaultMargin); CGPathAddLineToPoint(path, NULL, maxx, miny); CGPathAddLineToPoint(path, NULL, minx, miny); CGPathCloseSubpath(path); // Fill and stroke the path CGContextSaveGState(c); CGContextAddPath(c, path); CGContextClip(c); CGFloat locations[2] = { 0.0, 1.0 }; CGFloat mycomponents[8] = TABLE_CELL_BACKGROUND; CGColorSpaceRef myColorspace = CGColorSpaceCreateDeviceRGB(); myGradient = CGGradientCreateWithColorComponents(myColorspace, mycomponents, locations, 2); CGContextDrawLinearGradient(c, myGradient, CGPointMake(minx,miny), CGPointMake(minx,maxy), 0); CGContextRestoreGState(c); CGContextAddPath(c, path); CGContextStrokePath(c); 

What can I do to smooth the edges while maintaining a constant edge thickness in all cells?

+4
source share
2 answers

Your line width is set to 2 points. What happens is that your code computes your bounding box without understanding the line width. As a result, it turns out that for each straight section of your form, only half the stroke width is visible. The full width of the stroke is visible on the arc.

Here is the appropriate code segment from my Funversation app to draw game cards with rounded corners similar to what you have.

 CGRect rect = [self bounds]; rect.size.width -= lineWidth; rect.size.height -= lineWidth; rect.origin.x += lineWidth / 2.0; rect.origin.y += lineWidth / 2.0; 

Add that before calculating for minx, midx, maxx, etc. and the strokes for your shape should be uniform.

+7
source

Another way to make the beat consistent is to move the AddPath and StrokePath calls over the RestoreGState call β€” that is, a hit on the cutoff.

For a truly push-pull stroke with this solution, simply double the line width that you entered in the graphic state (i.e. set it to 4 pt), since half of it will be cut.

+1
source

Source: https://habr.com/ru/post/1300001/


All Articles