6

I'm attempting to build a UIImage in code using CoreGraphics (via PaintCode) that has a border and a corner radius. I'm finding that the image has a noticeably thicker border around the corner. This seems like it would either be an iOS bug or something that I'm completely missing. Please advise.

Code:

CGRect rect = CGRectMake(0, 0, 53, 100);

//// UIGraphics for UIImage context
CGContextRef context = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(context);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);

//// Rectangle Drawing
UIBezierPath *rectanglePath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius];
[backgroundColor setFill];
[rectanglePath fill];
[borderColor setStroke];
rectanglePath.lineWidth = 1.4;
[rectanglePath stroke];

//// UIBezierPath to Image
CGContextAddPath(context, rectanglePath.CGPath);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsPopContext();
UIGraphicsEndImageContext();

return image;

Image:

thicker corner radius

Here's what a lineWidth of 1 and width of 60 looks like, it still seems a little thick:

enter image description here

michaellindahl
  • 2,012
  • 5
  • 36
  • 64
  • My guess is it's an artifact of using a fractional line width. It's doing some interpolating to give you what you ask for. Try using 1.0 or 2.0 as a line width and I bet you get even results. (For that matter, on a Retina device 1.5 (points) should resolve to 3 pixels.) – Duncan C Aug 03 '15 at 19:38
  • Great thought, but it still looks funky with a 1.0 lineWidth and 60 width. (attached image to question). Granted that does help the issue, but doesn't fix it entirely. – michaellindahl Aug 03 '15 at 20:11
  • I find I get better rounded rectangle drawing using layer properties than I do using Core graphics. Not sure why. Try setting the lineWidth, borderColor, and borderWidth on your view's layer and see if that gives better results. – Duncan C Aug 03 '15 at 20:18

2 Answers2

5

For those of you following along at home:

Thanks to the helpful @PixelCutCompany I need to inset the bounds for the UIBezierPath so that the border doesn't exceed the frame of the image I am drawing.

Modified the code as follows for a lineWidth of 1.

CGRect boundedRectForRadius = CGRectMake(1, 1, 58, 98);
UIBezierPath *rectanglePath = [UIBezierPath bezierPathWithRoundedRect:boundedRectForRadius cornerRadius:cornerRadius];

Without this, it was cropping the image as so:

enter image description here

michaellindahl
  • 2,012
  • 5
  • 36
  • 64
0

The problem also can be in shift real screen pixels coordinates. Please check this discussion for more details: Core Graphics is not drawing a line at the correct width

Community
  • 1
  • 1
Vitalii Gozhenko
  • 9,220
  • 2
  • 48
  • 66