QuartzCore - Adding Rounded Corners to a Polygon - iphone

I'm attempting to draw a translucent black rectangle with a triangle cut out of the center.
I have this working perfectly with the code below. However, I'd like to round the corners of the triangle.
I've tried a couple of different techniques for adding rounded corners such as setting CGContextSetLineCap for a stroke and by creating my path with quartz and using CGContextAddArcToPoint, but I've failed to get anything to work.
As I mentioned, the code below works for a triangle cutout. How can I round the corners of the triangle?
CGContextRef context = UIGraphicsGetCurrentContext();
CGPoint position = CGPointMake(rect.size.width/2, rect.size.height * .7);
CGSize size = CGSizeMake(rect.size.width*.8, rect.size.height*.5);
CGFloat firstPointX = (position.x - (size.width / 2));
CGFloat firstPointY = (position.y - (size.height));
CGPoint firstPoint = CGPointMake(firstPointX, firstPointY);
CGFloat secondPointX = position.x + (size.width / 2);
CGFloat secondPointY = position.y - (size.height);
CGPoint secondPoint = CGPointMake(secondPointX, secondPointY);
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:position];
[path addLineToPoint:firstPoint];
[path moveToPoint:firstPoint];
[path addLineToPoint:secondPoint];
[path addLineToPoint:position];
[path closePath];
CGContextAddRect(context, rect);
CGContextAddPath(context, path.CGPath);
CGContextEOClip(context);
UIColor *translucentColor = [UIColor colorWithWhite:0 alpha:0.5];
CGContextSetFillColorWithColor(context, translucentColor.CGColor);
CGContextFillRect(context, rect);
UIGraphicsEndImageContext();
EDIT: Here's an example of what I'm trying to accomplish.

I think you want to use CGContextAddArc. It draws part of a circle with a line leading up to it if necessary. Here's the code to draw a rounded box that fills a UIView. For a triangle you'd have 3 lines instead of 4. Two on the top and one in the middle on the bottom. This is from a roundBoxView class I have:
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect boxRect = self.bounds;
float bRadius = self.cornerRadius;
float shrink = self.strokeThickness/2;
CGContextBeginPath(context);
// instead of this gray you could later add options for other colors
CGContextSetGrayFillColor(context, 0.0f, self.backgroundOpacity);
CGContextMoveToPoint(context, CGRectGetMinX(boxRect)+shrink + bRadius, CGRectGetMinY(boxRect)+shrink);
CGContextAddArc(context, CGRectGetMaxX(boxRect)-shrink - bRadius, CGRectGetMinY(boxRect)+shrink + bRadius, bRadius, 3 * (float)M_PI / 2, 0, 0);
CGContextAddArc(context, CGRectGetMaxX(boxRect)-shrink - bRadius, CGRectGetMaxY(boxRect)-shrink - bRadius, bRadius, 0, (float)M_PI / 2, 0);
CGContextAddArc(context, CGRectGetMinX(boxRect)+shrink + bRadius, CGRectGetMaxY(boxRect)-shrink - bRadius, bRadius, (float)M_PI / 2, (float)M_PI, 0);
CGContextAddArc(context, CGRectGetMinX(boxRect)+shrink + bRadius, CGRectGetMinY(boxRect)+shrink + bRadius, bRadius, (float)M_PI, 3 * (float)M_PI / 2, 0);
CGContextClosePath(context);
CGContextFillPath(context);
Of course instead of the boxRect being the full bounds you could pass that to your method and draw it using whatever bounds you want. To make it a triangle you would only have the 3 lines instead of two and you might have to do some math to figure out the start and end angles. On a box those angles are always 90 degrees (here given is icky radians) but on a triangle you'll either have to calc the angles on the fly or have a preset aspect ratio on the triangle so you can use preset start and stop angles. In the example as pictured with 3 equal angles you'd do 120 degrees or M_PI / 1.5 sized steps.

Related

How can I create a part of a filled circle using Core Graphics/Quartz

I have made a subclass of UIView and I am trying to draw part of a circle in my drawRect method.
I have tried using bezierPathWithArcCenter and filling it but that only result in a pie shape (image 3) and that's not what i'm after. I want to draw what you see in image 1 and 2.
Maybe I can clip a full circle somehow? The area around the circle needs to be transparent.
TompaLompas answer pointed me in the right direction (with the arc drawing part). However the complete solution and answer is like this:
#define DEGREES_TO_RADIANS(degrees) ((M_PI * degrees)/ 180)
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
CGContextRef ctx = UIGraphicsGetCurrentContext();
int radius = self.frame.size.width / 2;
CGPoint center = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
//Image 2
CGContextSetFillColorWithColor(ctx, [UIColor redColor].CGColor);
CGContextAddArc(ctx, center.x, center.y, radius, DEGREES_TO_RADIANS(225), DEGREES_TO_RADIANS(315), NO);
CGContextDrawPath(ctx, kCGPathFill);
}
try overriding drawRect with this:
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
float radius = 50.0f;
float x_left = rect.origin.x;
float x_left_center = x_left + radius;
float y_top = rect.origin.y;
float y_top_center = y_top + radius;
/* Begin path */
CGFloat white[4] = {0.0f, 204.0f/255.0f, 1.0f, 0.8f};
CGContextSetFillColor(context, white);
CGContextSetLineWidth(context, 1.0);
CGContextBeginPath(context);
CGContextMoveToPoint(context, x_left, y_top_center);
CGContextAddArcToPoint(context, x_left, y_top, x_left_center, y_top, radius);
CGContextAddLineToPoint(context,x_left, y_top + radius);
CGContextFillPath(context);
}
It will draw a rotated image number 2

How to create Hexagon in iPhone/iPad

I want to make UIView which is originally rectangular to Hexagon shape to be used in my application.
Please help me something on this.
Thanks in advance.
Subclass UView and override drawRect to draw a hexagon like so:
- (void)drawRect:(CGRect)rect
{
float polySize = 60; // change this
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGAffineTransform t0 = CGContextGetCTM(context);
t0 = CGAffineTransformInvert(t0);
CGContextConcatCTM(context, t0);
//Begin drawing setup
CGContextBeginPath(context);
CGContextSetRGBStrokeColor(context, 0, 0, 0, 1);
CGContextSetLineWidth(context, 2.0);
CGPoint center;
//Start drawing polygon
center = CGPointMake(160, 90.0);
CGContextMoveToPoint(context, center.x, center.y + polySize);
for(int i = 1; i < 6; ++i)
{
CGFloat x = polySize * sinf(i * 2.0 * M_PI / 6);
CGFloat y = polySize * cosf(i * 2.0 * M_PI / 6);
CGContextAddLineToPoint(context, center.x + x, center.y + y);
}
//Finish Drawing
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathStroke);
CGContextRestoreGState(context);
}
You can create a subclass of UIView and in it's -(void)drawRect: method draw a hexagon. Or Use UIImageView with image of hexagon

iPhone Core Animation - Drawing a Circle

I wish to create an animation. The best way I can explain this is if you can imagine drawing a circle. It starts at the top or 12 o clock and draws clockwise all the way around until it becomes a complete circle over the space of 10 or so seconds.
The closet I have come to this is to draw a point rotating around a center point using Core Animation (using the sample code here). But I am at a loss on how to draw the circle? Any suggestions are very welcome.
Many Thanks :)
What you really should do is to animate the stroke of a CAShapeLayer where the path is a circle. This will be accelerated using Core Animation and is less messy then to draw part of a circle in -drawRect:.
The code below will create a circle shape layer in the center of the screen and animate the stroke of it clockwise so that it looks as if it is being drawn. You can of course use any shape you'd like. (You can read this article on Ole Begemanns blog to learn more about how to animate the stroke of a shape layer.)
Note: that the stoke properties are not the same as the border properties on the layer. To change the width of the stroke you should use "lineWidth" instead of "borderWitdh" etc.
// Set up the shape of the circle
int radius = 100;
CAShapeLayer *circle = [CAShapeLayer layer];
// Make a circular shape
circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius)
cornerRadius:radius].CGPath;
// Center the shape in self.view
circle.position = CGPointMake(CGRectGetMidX(self.view.frame)-radius,
CGRectGetMidY(self.view.frame)-radius);
// Configure the apperence of the circle
circle.fillColor = [UIColor clearColor].CGColor;
circle.strokeColor = [UIColor blackColor].CGColor;
circle.lineWidth = 5;
// Add to parent layer
[self.view.layer addSublayer:circle];
// Configure animation
CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:#"strokeEnd"];
drawAnimation.duration = 10.0; // "animate over 10 seconds or so.."
drawAnimation.repeatCount = 1.0; // Animate only once..
// Animate from no part of the stroke being drawn to the entire stroke being drawn
drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
drawAnimation.toValue = [NSNumber numberWithFloat:1.0f];
// Experiment with timing to get the appearence to look the way you want
drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
// Add the animation to the circle
[circle addAnimation:drawAnimation forKey:#"drawCircleAnimation"];
Here is another solution to the problem, based off #David's answer. This approach lets you set the direction of the circle's animation, and offers slightly more control. Edit: I've written a blog post on how to draw a circle with Swift, which I'll try to keep up to date with the betas. Check there if the code below doesn't work for you.
let radius = 100.0
// Create the circle layer
var circle = CAShapeLayer()
// Set the center of the circle to be the center of the view
let center = CGPointMake(CGRectGetMidX(self.frame) - radius, CGRectGetMidY(self.frame) - radius)
let fractionOfCircle = 3.0 / 4.0
let twoPi = 2.0 * Double(M_PI)
// The starting angle is given by the fraction of the circle that the point is at, divided by 2 * Pi and less
// We subtract M_PI_2 to rotate the circle 90 degrees to make it more intuitive (i.e. like a clock face with zero at the top, 1/4 at RHS, 1/2 at bottom, etc.)
let startAngle = Double(fractionOfCircle) / Double(twoPi) - Double(M_PI_2)
let endAngle = 0.0 - Double(M_PI_2)
let clockwise: Bool = true
// `clockwise` tells the circle whether to animate in a clockwise or anti clockwise direction
circle.path = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: clockwise).CGPath
// Configure the circle
circle.fillColor = UIColor.blackColor().CGColor
circle.strokeColor = UIColor.redColor().CGColor
circle.lineWidth = 5
// When it gets to the end of its animation, leave it at 0% stroke filled
circle.strokeEnd = 0.0
// Add the circle to the parent layer
self.layer.addSublayer(circle)
// Configure the animation
var drawAnimation = CABasicAnimation(keyPath: "strokeEnd")
drawAnimation.repeatCount = 1.0
// Animate from the full stroke being drawn to none of the stroke being drawn
drawAnimation.fromValue = NSNumber(double: fractionOfCircle)
drawAnimation.toValue = NSNumber(float: 0.0)
drawAnimation.duration = 30.0
drawAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
// Add the animation to the circle
circle.addAnimation(drawAnimation, forKey: "drawCircleAnimation")
I got a solution to this problem, code below. I seem to have messed up in my explanation of the problem at hand so rewrote it as another question that got answered with the correct solution, see here
thanks everyone for their advice!
-(void)drawRect:(CGRect)rect
{
// Drawing code
CGRect allRect = self.bounds;
CGContextRef context = UIGraphicsGetCurrentContext();
// Draw background
CGContextSetRGBStrokeColor(context, self.strokeValueRed, self.strokeValueGreen, self.strokeValueBlue, self.strokeValueAlpha); // white
CGContextSetLineWidth(context, 5);
// Draw progress
CGPoint center = CGPointMake(allRect.size.width / 2, allRect.size.height / 2);
CGFloat radius = (allRect.size.width - 4) / 2;
CGFloat startAngle = - ((float)M_PI / 2); // 90 degrees
CGFloat endAngle = (self.progress * 2 * (float)M_PI) + startAngle;
CGContextAddArc(context, center.x, center.y, radius, startAngle, endAngle, 0);
CGContextStrokePath(context);
}
Ok I have a partial fix. I found the following code that draws segments of a circle. Its basically a UIView subclass that gets its drawRect fired every time its progress should be updated. The only question I have now is how would I change it so that instead of drawing sections or slices it would just draw the circle stroke?
-(void)drawRect:(CGRect)rect
{
// Drawing code
CGRect allRect = self.bounds;
CGRect circleRect = CGRectInset(allRect, 2.0f, 2.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
// Draw background
CGContextSetRGBStrokeColor(context, self.strokeValueRed, self.strokeValueGreen, self.strokeValueBlue, self.strokeValueAlpha); // white
CGContextSetRGBFillColor(context, 1.0f, 1.0f, 1.0f, 0.1f); // translucent white
CGContextSetLineWidth(context, self.lineWidth);
CGContextFillEllipseInRect(context, circleRect);
CGContextStrokeEllipseInRect(context, circleRect);
// Draw progress
CGPoint center = CGPointMake(allRect.size.width / 2, allRect.size.height / 2);
CGFloat radius = (allRect.size.width - 4) / 2;
CGFloat startAngle = - ((float)M_PI / 2); // 90 degrees
CGFloat endAngle = (self.progress * 2 * (float)M_PI) + startAngle;
CGContextSetRGBFillColor(context, 1.0f, 1.0f, 1.0f, 1.0f); // white
CGContextMoveToPoint(context, center.x, center.y);
CGContextAddArc(context, center.x, center.y, radius, startAngle, endAngle, 0);
CGContextClosePath(context);
CGContextFillPath(context);
}

Draw a rounded UIView with gradient and drop shadow

EDIT:
I finally found a real simple solution to this problem, using the CAGradientLayer class, and the CALayer drawing functionalities.
Ole Begemann released a great UIView wrapper for CAGradientLayer class named OBGradientView.
This class allows you to easily create a gradient UIView in your application.
You then use the CALayer drawing functionalities to add the rounded corners and drop shadow values :
// Create the gradient view
OBGradientView *gradient = [[OBGradientView alloc] initWithFrame:someRect];
NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor yellowColor], nil];
gradient.colors = colors;
// Set rounded corners and drop shadow
gradient.layer.cornerRadius = 5.0;
gradient.layer.shadowColor = [UIColor grayColor].CGColor;
gradient.layer.shadowOpacity = 1.0;
gradient.layer.shadowOffset = CGSizeMake(2.0, 2.0);
gradient.layer.shadowRadius = 3.0;
[self.view addSubview:gradient];
[gradient release];
Dont forget to add the QuartzCore framework to your project.
ORIGINAL QUESTION:
I have been working on a custom control that is a rounded rectangle button, filled with a linear gradient, and having a drop shadow.
I have filled the two first steps using this answer : link text
My problem is now to add a drop shadow under the resulting shape.
Actually, the context has been clipped to the rounded rect path, so when I use the CGContextSetShadow function, it doesn't draw it.
I tried to solve this problem by drawing the rounded rect twice, first with a plain color, so it draws the shadow, and then redraw it with the gradient fill.
It kinda worked, but I still can see a few pixels at the corners of the shape resulting from the first draw with a plain color, as you can see on this zoomed version :
http://img269.imageshack.us/img269/6489/capturedcran20100701192.png
It is almost good, but not perfect yet...
Here is my -drawRect: implementation :
static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight)
{
float fw, fh;
if (ovalWidth == 0 || ovalHeight == 0) {
CGContextAddRect(context, rect);
return;
}
CGContextSaveGState(context);
CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGContextScaleCTM (context, ovalWidth, ovalHeight);
fw = CGRectGetWidth (rect) / ovalWidth;
fh = CGRectGetHeight (rect) / ovalHeight;
CGContextMoveToPoint(context, fw, fh/2);
CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);
CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);
CGContextClosePath(context);
CGContextRestoreGState(context);
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGSize shadowOffset = CGSizeMake(10.0, 10.0);
CGFloat blur = 5.0;
rect.size.width -= shadowOffset.width + blur;
rect.size.height -= shadowOffset.height + blur;
CGContextSaveGState(context);
addRoundedRectToPath(context, rect, _radius, _radius);
CGContextSetShadow (context, shadowOffset, blur);
CGContextDrawPath(context, kCGPathFill);
CGContextRestoreGState(context);
addRoundedRectToPath(context, rect, _radius, _radius);
CGContextClip(context);
CGFloat colors[] =
{
_gradientStartColor.red, _gradientStartColor.green, _gradientStartColor.blue, _gradientStartColor.alpha,
_gradientEndColor.red, _gradientEndColor.green, _gradientEndColor.blue, _gradientEndColor.alpha
};
size_t num_locations = 2;
CGFloat locations[2] = { 0.0, 1.0 };
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(rgb, colors, locations, num_locations);
CGRect currentBounds = self.bounds;
CGPoint gStartPoint = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);
CGPoint gEndPoint = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMaxY(currentBounds));
CGContextDrawLinearGradient(context, gradient, gStartPoint, gEndPoint, 0);
CGColorSpaceRelease(rgb);
CGGradientRelease(gradient);
}
Any ideas on how to do this in another way ?
Thanks !
In order to create a rounded corner view with a gradient background and drop shadow, here's what did:
The first part is very similar to what was provided in the question, it creates a rounded rect path using CGPathAddArcToPoint as described very well in this article. Here's a picture to help me understand it:
The second part works as follows:
Enable shadowing on the graphics context, add the path that was just defined, then fill that path. You can't apply the shadow to just the path itself (paths are not part of the graphics state), so you need to fill the path in order for the shadow to appear (I suppose a stroked path might also work?). You can't simply apply the shadow to a gradient since it's not really a standard fill (see this post for more info).
Once you have a filled rounded rect that creates the shadow, you need to draw the gradient over top of that. So add the path a second time in order to set the clipping area, then draw the gradient using CGContextDrawLinearGradient. I don't think you can easily "fill" a path with a gradient like you could with the earlier standard-fill step, so instead you fill the drawing area with the gradient and then clip to the rounded rectangle area that you're interested in.
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
CGGradientRef gradient = [self normalGradient];
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGMutablePathRef outlinePath = CGPathCreateMutable();
float offset = 5.0;
float w = [self bounds].size.width;
float h = [self bounds].size.height;
CGPathMoveToPoint(outlinePath, nil, offset*2.0, offset);
CGPathAddArcToPoint(outlinePath, nil, offset, offset, offset, offset*2, offset);
CGPathAddLineToPoint(outlinePath, nil, offset, h - offset*2.0);
CGPathAddArcToPoint(outlinePath, nil, offset, h - offset, offset *2.0, h-offset, offset);
CGPathAddLineToPoint(outlinePath, nil, w - offset *2.0, h - offset);
CGPathAddArcToPoint(outlinePath, nil, w - offset, h - offset, w - offset, h - offset * 2.0, offset);
CGPathAddLineToPoint(outlinePath, nil, w - offset, offset*2.0);
CGPathAddArcToPoint(outlinePath, nil, w - offset , offset, w - offset*2.0, offset, offset);
CGPathCloseSubpath(outlinePath);
CGContextSetShadow(ctx, CGSizeMake(4,4), 3);
CGContextAddPath(ctx, outlinePath);
CGContextFillPath(ctx);
CGContextAddPath(ctx, outlinePath);
CGContextClip(ctx);
CGPoint start = CGPointMake(rect.origin.x, rect.origin.y);
CGPoint end = CGPointMake(rect.origin.x, rect.size.height);
CGContextDrawLinearGradient(ctx, gradient, start, end, 0);
CGPathRelease(outlinePath);
}
- (CGGradientRef)normalGradient
{
NSMutableArray *normalGradientLocations = [NSMutableArray arrayWithObjects:
[NSNumber numberWithFloat:0.0f],
[NSNumber numberWithFloat:1.0f],
nil];
NSMutableArray *colors = [NSMutableArray arrayWithCapacity:2];
UIColor *color = [UIColor colorWithRed:0.2745 green:0.2745 blue:0.2745 alpha:1.0];
[colors addObject:(id)[color CGColor]];
color = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];
[colors addObject:(id)[color CGColor]];
NSMutableArray *normalGradientColors = colors;
int locCount = [normalGradientLocations count];
CGFloat locations[locCount];
for (int i = 0; i < [normalGradientLocations count]; i++)
{
NSNumber *location = [normalGradientLocations objectAtIndex:i];
locations[i] = [location floatValue];
}
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGGradientRef normalGradient = CGGradientCreateWithColors(space, (CFArrayRef)normalGradientColors, locations);
CGColorSpaceRelease(space);
return normalGradient;
}
I have solution that does not need pre-fill of the path. Advantage(?) is that the shadow can use transparency effects of the gradient (i.e. if gradient is from opaque to trasparent, shadow will be partially transparent as well) and is simpler.
It goes more or less like:
CGContextSetShadowWithColor();
CGContextBeginTransparencyLayer();
CGContextSaveGState();
CGContextClip();
CGGradientCreateWithColorComponents();
CGContextRestoreGState();
CGContextEndTransparencyLayer();
CGContextSetShadowWithColor(..., NULL);
I suppose that is beacuse CGContextBeginTransparencyLayer/CGContextEndTransparencyLayer is outside the clip and the shadow is applied to that layer (which contains gradient filled path). At least it seems to work for me.
For shadows you can use CGContextSetShadow()
This code will draw something with a shadow:
- (void)drawTheRealThingInContext:(CGContextRef)ctx
{
// calculate x, y, w, h and inset here...
CGContextMoveToPoint(ctx, x+inset, y);
CGContextAddLineToPoint(ctx, x+w-inset, y);
CGContextAddArcToPoint(ctx, x+w, y, x+w, y+inset, inset);
CGContextAddLineToPoint(ctx, x+w, y+w-inset);
CGContextAddArcToPoint(ctx,x+w, y+w, x+w-inset, y+w, inset);
CGContextAddLineToPoint(ctx, x+inset, y+w);
CGContextAddArcToPoint(ctx,x, y+w, x, y+w-inset, inset);
CGContextAddLineToPoint(ctx, x, y+inset);
CGContextAddArcToPoint(ctx,x, y, x+inset, y, inset);
}
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGFloat color[4];color[0] = 1.0;color[1] = 1.0;color[2] = 1.0;color[3] = 1.0;
CGFloat scolor[4];scolor[0] = 0.4;scolor[1] = 0.4;scolor[2] = 0.4;scolor[3] = 0.8;
CGContextSetFillColor(ctx, color);
CGContextSaveGState(ctx);
CGSize myShadowOffset = CGSizeMake (3, -3);
CGContextSetShadow (ctx, myShadowOffset, 1);
CGContextBeginPath(ctx);
[self drawTheRealThingInContext:ctx];
CGContextFillPath(ctx);
CGContextRestoreGState(ctx);
}
Your (original) problem was that you were again drawing a shadow when you drew the gradient. This shadow had a (0,0) offset and a little bit of blur, that only shines through on the corners. In the line before CGContextDrawLinearGradient(…), add the following:
CGContextSetShadowWithColor(context, CGSizeMake(0, 0), 0, NULL);
The NULL color value disables shadowing and will remove the corner effect.

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()