Smoothing a rounded stroke in Core Graphics - iphone

I am creating my own UITableViewCells with a gradient background. I have all the logic and drawing worked out, but one thing I want to fix is the "chunkiness" around the corners of my custom cell:
alt text http://grab.by/27SM
If you zoom in on the corners, you can see what I am talking about. Here is the code I a using to generate 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 keeping a consistent edge thickness across all cells?

Your line width is set to 2 points. What's happening is that your code is calculating your bounding rect without understanding the width of the line. The result is that for every straight segment of your shape, only half of the stroke's width is visible. On the arc, the full stroke width is visible.
Here's the relevant segment of code from my app, Funversation, to draw the playing 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 your calculation for minx, midx, maxx, etc. and the strokes for your shape should be uniform.

The other way to make the stroke consistent would be to move the AddPath and StrokePath calls up above the RestoreGState call—that is, stroke while clipped.
For a truly 2-pt-wide stroke with this solution, simply double the line width you put in the graphics state (i.e., set it to 4 pt), since half of it will be clipped out.

Related

adding white border along a circle UIImage

I have generated a circle UIImage using a mask as following (where masked_circle is a black circle):
CGContextRef context = UIGraphicsGetCurrentContext();
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
UIImage *maskImage = [UIImage imageNamed:#"masked_circle.png"];
CGImageRef maskImageRef = [maskImage CGImage];
// create a bitmap graphics context the size of the image
CGContextRef mainViewContentContext = CGBitmapContextCreate (NULL, maskImage.size.width, maskImage.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
CGFloat ratio = 0;
ratio = maskImage.size.width/ self.image_.size.width;
if(ratio * self.image_.size.height < maskImage.size.height) {
ratio = maskImage.size.height/ self.image_.size.height;
}
CGRect rect1 = {{0, 0}, {maskImage.size.width, maskImage.size.height}};
CGRect rect2 = {{-((self.image_.size.width*ratio)-maskImage.size.width)/2 , -((self.image_.size.height*ratio)-maskImage.size.height)/2}, {self.image_.size.width*ratio, self.image_.size.height*ratio}};
CGContextClipToMask(mainViewContentContext, rect1, maskImageRef);
CGContextDrawImage(mainViewContentContext, rect2, self.image_.CGImage);
CGImageRef newImage = CGBitmapContextCreateImage(mainViewContentContext);
CGContextRelease(mainViewContentContext);
UIImage *theImage = [UIImage imageWithCGImage:newImage];
Now after this I wanted to add a 1px white border around the circle image, how can I do so?
Here's a much simpler solution to turn any view, but specifically a UIImageView into a circle with a border of varying size and color. This of course assumes you're dealing with a square image like an icon.
#import <UIKit/UIKit.h>
#interface UIView (Shapes)
- (void)makeCircle;
- (void)makeCircleWithBorderColor:(UIColor *) color Width:(CGFloat) width;
#end
#implementation UIView (Shapes)
- (void)makeCircle {
CALayer *lyr = self.layer;
lyr.masksToBounds = YES;
lyr.cornerRadius = self.bounds.size.width / 2; // assumes image is a square
}
- (void)makeCircleWithBorderColor:(UIColor *) color Width:(CGFloat) width {
[self makeCircle];
CALayer *lyr = self.layer;
lyr.borderWidth = width;
lyr.borderColor = [color CGColor];
}
#end
Here's some code that draws a border around a frame with a corner radius. Make that radius equal to half size and you've got a circle!
CGFloat strokeWidth =1.0;
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, strokeWidth);
CGContextSetStrokeColorWithColor(context, [UIColor grayColor].CGColor);
CGFloat radius = 7.0;
CGRect rrect = self.bounds;
rrect.size.width = rrect.size.width - strokeWidth*2;
rrect.size.height = rrect.size.height - strokeWidth*2;
rrect.origin.x = rrect.origin.x + (strokeWidth / 2);
rrect.origin.y = rrect.origin.y + (strokeWidth / 2);
CGFloat width = CGRectGetWidth(rrect);
CGFloat height = CGRectGetHeight(rrect);
if (radius > width/2.0)
radius = width/2.0;
if (radius > height/2.0)
radius = height/2.0;
CGFloat minx = CGRectGetMinX(rrect);
CGFloat midx = CGRectGetMidX(rrect);
CGFloat maxx = CGRectGetMaxX(rrect);
CGFloat miny = CGRectGetMinY(rrect);
CGFloat midy = CGRectGetMidY(rrect);
CGFloat maxy = CGRectGetMaxY(rrect);
CGContextMoveToPoint(context, minx, midy);
CGContextAddArcToPoint(context, minx, miny, midx, miny, radius);
CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius);
CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius);
CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius);
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFillStroke);

Join two Rects in Core Graphics

I'm trying to get into Core Graphics.
A the Moment I'm trying to draw a certain shape out of 2 rects. Now I want to join those booth to work with gradient and color functions. I'm not sure if there even is a way.
Here is a Picture:
Here are my Code Snippets:
-(void)drawRoundedRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect frame1 = CGRectMake(self.bounds.origin.x, self.bounds.origin.y+45, self.bounds.size.width, self.bounds.size.height-45);
CGRect frame2 = CGRectMake(self.bounds.size.width-80, self.bounds.origin.y+25, 80, 50);
CGPathRef roundedRectPath1 = [self newPathForRoundedRect:frame1 radius:15];
CGPathRef roundedRectPath2 = [self newPathForRoundedRect:frame2 radius:11];
CGContextSetRGBFillColor(ctx, 200, 200, 200, 0.5);
CGContextAddPath(ctx, roundedRectPath1);
CGContextFillPath(ctx);
CGPathRelease(roundedRectPath1);
CGContextAddPath(ctx, roundedRectPath2);
CGContextFillPath(ctx);
CGPathRelease(roundedRectPath2);
}
-(CGPathRef) newPathForRoundedRect:(CGRect)rect radius:(CGFloat)radius
{
CGMutablePathRef retPath = CGPathCreateMutable();
CGRect innerRect = CGRectInset(rect, radius, radius);
CGFloat inside_right = innerRect.origin.x + innerRect.size.width;
CGFloat outside_right = rect.origin.x + rect.size.width;
CGFloat inside_bottom = innerRect.origin.y + innerRect.size.height;
CGFloat outside_bottom = rect.origin.y + rect.size.height;
CGFloat inside_top = innerRect.origin.y;
CGFloat outside_top = rect.origin.y;
CGFloat outside_left = rect.origin.x;
CGPathMoveToPoint(retPath, NULL, innerRect.origin.x, outside_top);
CGPathAddLineToPoint(retPath, NULL, inside_right, outside_top);
CGPathAddArcToPoint(retPath, NULL, outside_right, outside_top, outside_right, inside_top, radius);
CGPathAddLineToPoint(retPath, NULL, outside_right, inside_bottom);
CGPathAddArcToPoint(retPath, NULL, outside_right, outside_bottom, inside_right, outside_bottom, radius);
CGPathAddLineToPoint(retPath, NULL, innerRect.origin.x, outside_bottom);
CGPathAddArcToPoint(retPath, NULL, outside_left, outside_bottom, outside_left, inside_bottom, radius);
CGPathAddLineToPoint(retPath, NULL, outside_left, inside_top);
CGPathAddArcToPoint(retPath, NULL, outside_left, outside_top, innerRect.origin.x, outside_top, radius);
CGPathCloseSubpath(retPath);
return retPath;
}
You're doing way too much work here. Just use UIBezierPath's +bezierPathWithRoundedRect:cornerRadius: and – appendPath: methods.
CGRect rect1, rect2;
CGFloat radius;
// fill in the values you want for the rects and the radius
UIBezierPath *result =
[UIBezierPath bezierPathWithRoundedRect: rect1 cornerRadius:radius];
[result appendPath:
[UIBezierPath bezierPathWithRoundedRect: rect2 cornerRadius:radius];
// result is now a path comprising both of the roundrects. You can fill it with a gradient like any other path.
You have some options:
Construct a new path that forms the union of the two separate paths without intersections. Core Graphics would not help you with this approach, it does not provide boolean path operations.
Use a transparency layer to draw both shapes (one after each other). This would fix the overlapping area but it wouldn't work with gradients.
Create a bitmap context to create a mask. Draw both shapes into the mask. Then clip to the mask in your original context and draw a rect over the bounding box of your shape.

How to draw a rounded rectangle in Core Graphics / Quartz 2D?

I need to draw an outline for a rounded rectangle. I know I can make lines and arcs, but maybe there is also a function for rounded rects?
Instead of making your own path out of lines and arcs, you can use
[UIBezierPath bezierPathWithRoundedRect:cornerRadius:]
or
[UIBezierPath bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:]
(the second one lets you specify which corners are rounded)
Available in iOS 3.2 or later.
There is no prepackaged way to this, you must combine arcs in order to do this, apples quartzdemo project shows the code to do this, here is a reference Quartz Demo and here is the code they provide
// As a bonus, we'll combine arcs to create a round rectangle!
// Drawing with a white stroke color
CGContextRef context=UIGraphicsGetCurrentContext()
CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
// If you were making this as a routine, you would probably accept a rectangle
// that defines its bounds, and a radius reflecting the "rounded-ness" of the rectangle.
CGRect rrect = CGRectMake(210.0, 90.0, 60.0, 60.0);
CGFloat radius = 10.0;
// NOTE: At this point you may want to verify that your radius is no more than half
// the width and height of your rectangle, as this technique degenerates for those cases.
// In order to draw a rounded rectangle, we will take advantage of the fact that
// CGContextAddArcToPoint will draw straight lines past the start and end of the arc
// in order to create the path from the current position and the destination position.
// In order to create the 4 arcs correctly, we need to know the min, mid and max positions
// on the x and y lengths of the given rectangle.
CGFloat minx = CGRectGetMinX(rrect), midx = CGRectGetMidX(rrect), maxx = CGRectGetMaxX(rrect);
CGFloat miny = CGRectGetMinY(rrect), midy = CGRectGetMidY(rrect), maxy = CGRectGetMaxY(rrect);
// Next, we will go around the rectangle in the order given by the figure below.
// minx midx maxx
// miny 2 3 4
// midy 1 9 5
// maxy 8 7 6
// Which gives us a coincident start and end point, which is incidental to this technique, but still doesn't
// form a closed path, so we still need to close the path to connect the ends correctly.
// Thus we start by moving to point 1, then adding arcs through each pair of points that follows.
// You could use a similar tecgnique to create any shape with rounded corners.
// Start at 1
CGContextMoveToPoint(context, minx, midy);
// Add an arc through 2 to 3
CGContextAddArcToPoint(context, minx, miny, midx, miny, radius);
// Add an arc through 4 to 5
CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius);
// Add an arc through 6 to 7
CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius);
// Add an arc through 8 to 9
CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius);
// Close the path
CGContextClosePath(context);
// Fill & stroke the path
CGContextDrawPath(context, kCGPathFillStroke);
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:bubbleBounds cornerRadius:15.0];
CGContextSetStrokeColorWithColor(context, [UIColor grayColor].CGColor);
[bezierPath stroke];
Here is a function I wrote that rounds the input rect using a corner radius.
CGMutablePathRef createRoundedCornerPath(CGRect rect, CGFloat cornerRadius) {
// create a mutable path
CGMutablePathRef path = CGPathCreateMutable();
// get the 4 corners of the rect
CGPoint topLeft = CGPointMake(rect.origin.x, rect.origin.y);
CGPoint topRight = CGPointMake(rect.origin.x + rect.size.width, rect.origin.y);
CGPoint bottomRight = CGPointMake(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);
CGPoint bottomLeft = CGPointMake(rect.origin.x, rect.origin.y + rect.size.height);
// move to top left
CGPathMoveToPoint(path, NULL, topLeft.x + cornerRadius, topLeft.y);
// add top line
CGPathAddLineToPoint(path, NULL, topRight.x - cornerRadius, topRight.y);
// add top right curve
CGPathAddQuadCurveToPoint(path, NULL, topRight.x, topRight.y, topRight.x, topRight.y + cornerRadius);
// add right line
CGPathAddLineToPoint(path, NULL, bottomRight.x, bottomRight.y - cornerRadius);
// add bottom right curve
CGPathAddQuadCurveToPoint(path, NULL, bottomRight.x, bottomRight.y, bottomRight.x - cornerRadius, bottomRight.y);
// add bottom line
CGPathAddLineToPoint(path, NULL, bottomLeft.x + cornerRadius, bottomLeft.y);
// add bottom left curve
CGPathAddQuadCurveToPoint(path, NULL, bottomLeft.x, bottomLeft.y, bottomLeft.x, bottomLeft.y - cornerRadius);
// add left line
CGPathAddLineToPoint(path, NULL, topLeft.x, topLeft.y + cornerRadius);
// add top left curve
CGPathAddQuadCurveToPoint(path, NULL, topLeft.x, topLeft.y, topLeft.x + cornerRadius, topLeft.y);
// return the path
return path;
}
How to use the function, assuming you subclass UIView and override drawRect:
- (void)drawRect:(CGRect)rect {
// constants
const CGFloat outlineStrokeWidth = 20.0f;
const CGFloat outlineCornerRadius = 15.0f;
const CGColorRef whiteColor = [[UIColor whiteColor] CGColor];
const CGColorRef redColor = [[UIColor redColor] CGColor];
// get the context
CGContextRef context = UIGraphicsGetCurrentContext();
// set the background color to white
CGContextSetFillColorWithColor(context, whiteColor);
CGContextFillRect(context, rect);
// inset the rect because half of the stroke applied to this path will be on the outside
CGRect insetRect = CGRectInset(rect, outlineStrokeWidth/2.0f, outlineStrokeWidth/2.0f);
// get our rounded rect as a path
CGMutablePathRef path = createRoundedCornerPath(insetRect, outlineCornerRadius);
// add the path to the context
CGContextAddPath(context, path);
// set the stroke params
CGContextSetStrokeColorWithColor(context, redColor);
CGContextSetLineWidth(context, outlineStrokeWidth);
// draw the path
CGContextDrawPath(context, kCGPathStroke);
// release the path
CGPathRelease(path);
}
Example output:
If you want To have rounded corners on any UIView (or subclass) the easy way is to set the cornerRadius property on the view's layer. See Preview rounded image in iphone
CGPathCreateWithRoundedRect() will do what you want.
CGPathRef CGPathCreateWithRoundedRect(
CGRect rect,
CGFloat cornerWidth,
CGFloat cornerHeight,
const CGAffineTransform *transform
);
Available starting in iOS 7.0
Swift:
let rect: CGRect = ...
let path = UIBezierPath(roundedRect: rect, cornerRadius: 5.0)
context.addPath(path.cgPath)
context.setStrokeColor(UIColor.clear.cgColor)
context.drawPath(using: .fillStroke)
Maybe... three? years late, but these days I'm using this without issues.
#import CoreGraphics;
#interface YourViewController ()
#property (weak, nonatomic) IBOutlet UIButton *theButton;
#end
- (void)viewDidLoad
{
[super viewDidLoad];
self.theButton.layer.cornerRadius = 5.0f;
self.theButton.layer.masksToBounds = YES;
// Another useful ones
// Scaling the view (width, height)
self.theButton.transform = CGAfflineTransformMakeScale(1.50f, 1.50f);
// Setting an alpha value (transparency) - nice with Activity Indicator subviews
self.theButton.alpha = 0.8f;
}
Swift 4.2
let lineWidth: CGFloat = 5.0
let path = UIBezierPath(roundedRect: rect.insetBy(dx: lineWidth/2.0, dy: lineWidth/2.0), cornerRadius: 10。0)
path.lineWidth = lineWidth
UIColor.green.setStroke()
path.stroke()

Rounded UIView with Shadow?

So using this link:
How do I draw a shadow under a UIView?
And this link:
http://iphonedevelopment.blogspot.com/2008/11/creating-transparent-uiviews-rounded.html
I came upon this implementation:
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetShadow(context, CGSizeMake(-15.0f, 20.0f), 5.0f);
CGContextSetLineWidth(context, strokeWidth);
CGContextSetStrokeColorWithColor(context, self.strokeColor.CGColor);
CGContextSetFillColorWithColor(context, self.rectColor.CGColor);
CGRect rrect = self.bounds;
CGFloat radius = cornerRadius;
CGFloat width = CGRectGetWidth(rrect);
CGFloat height = CGRectGetHeight(rrect);
// Make sure corner radius isn't larger than half the shorter side
if (radius > width/2.0)
radius = width/2.0;
if (radius > height/2.0)
radius = height/2.0;
CGFloat minx = CGRectGetMinX(rrect);
CGFloat midx = CGRectGetMidX(rrect);
CGFloat maxx = CGRectGetMaxX(rrect);
CGFloat miny = CGRectGetMinY(rrect);
CGFloat midy = CGRectGetMidY(rrect);
CGFloat maxy = CGRectGetMaxY(rrect);
CGContextMoveToPoint(context, minx, midy);
CGContextAddArcToPoint(context, minx, miny, midx, miny, radius);
CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius);
CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius);
CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius);
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFillStroke);
CGContextRestoreGState(context);
}
However when it draws, the shadow is clipped to the bounds of the view. I have tried setting self.clipsToBounds = NO however this doesn't affect the problem.
How about drawing the shadow using Quartz Core instead? Something like:
view.layer.shadowColor = [UIColor blackColor].CGColor;
view.layer.shadowOffset = CGSizeMake(0, 0);
view.layer.shadowRadius = 4;
view.layer.shadowOpacity = 1;
view.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:view.frame cornerRadius:11].CGPath; // make sure you set that for better performance

How can I clear the corners outside of a rounded rect using the iPhone SDK?

I am attempting to implement a custom view. This view should display an image surrounded by a gray, rounded rect border. I can get the image to display fine, as well as the border, however, since the border has rounded corners, I need a way to clear those corners such that they correctly display whatever is behind the view. How can I accomplish this?
It seems like I might be able to use CGContextClearRect, but then wouldn't I have to call this multiple times, reconstructing the area outside of my rounded corner? That sounds overly complicated.
Is there a better way to create this view?
Here is my current code:
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
// Draw the image. This will completely fill the current rect.
[image drawInRect:self.bounds];
// Ensure we draw completely within our bounds instead of straddling it.
CGRect rrect = self.bounds;
rrect.size.height = rrect.size.height - 1.0;
rrect.size.width = rrect.size.width - 1.0;
rrect.origin.x = rrect.origin.x + (1.0 / 2);
rrect.origin.y = rrect.origin.y + (1.0 / 2);
CGFloat radius = 5.0;
CGFloat minx = CGRectGetMinX(rrect);
CGFloat midx = CGRectGetMidX(rrect);
CGFloat maxx = CGRectGetMaxX(rrect);
CGFloat miny = CGRectGetMinY(rrect);
CGFloat midy = CGRectGetMidY(rrect);
CGFloat maxy = CGRectGetMaxY(rrect);
// Draw the rounded rect border.
CGContextSetRGBStrokeColor(context, 0.6, 0.6, 0.6, 1.0);
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 0.0);
CGContextSetLineWidth(context, 1.0);
CGContextMoveToPoint(context, minx, midy);
CGContextAddArcToPoint(context, minx, miny, midx, miny, radius);
CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius);
CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius);
CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius);
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFillStroke);
}
Add the rounded-rect path to the clipping path before drawing the image.
Last week I was trying to do something similar.
With your question, the answer and other Q&A I created an example with a solution.
https://github.com/GabrielMassana/TransparentRoudRectButton