1

Imagine a long rectangle (maybe with size 200x20). All sides have straight edges. In my iOS app, this is easy for me to draw:

CGContextFillRect(context, CGRectMake(xLoc, yLoc, 200, 20));

Now what if I wanted the shorter ends (on the left and right side of the rectangle) to be slightly curved, rather than straight edges. What would the code look like to do this?

(Note that I am relatively inexperienced with CGContext drawing)

CodeGuy
  • 28,427
  • 76
  • 200
  • 317

2 Answers2

2

Something like this (untested, so beware of bugs!):

- (void)drawRect:(CGRect)rect {
 CGContextRef context = UIGraphicsGetCurrentContext();
 CGContextSetStrokeColorWithColor(context, [[UIColor blackColor] CGColor]);
 CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);

 CGRect rrect = CGRectMake(CGRectGetMinX(rect), CGRectGetMinY(rect), CGRectGetWidth(rect)-30, CGRectGetHeight(rect)-30);
 CGFloat radius = 0.5f;

 CGFloat minx = CGRectGetMinX(rrect), midx = CGRectGetMidX(rrect), maxx = CGRectGetMaxX(rrect);
 CGFloat miny = CGRectGetMinY(rrect), midy = CGRectGetMidY(rrect), 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);
}
PengOne
  • 48,188
  • 17
  • 130
  • 149
  • can you modify that so that it's a method such as drawCurvedRectanlge:(CGRect)rect? which will draw a curved rectangle in place of a normal rectangle of size rect – CodeGuy Jul 01 '11 at 22:59
  • Yes, it can be done. Just add lines to points and so forth. I'll leave that exercise to you :-) – PengOne Jul 01 '11 at 23:01
  • @reising1: I don't have time at present, but if I remember and have time later, then I'll try to post it then. – PengOne Jul 01 '11 at 23:02
1

You may find Jeff LaMarche's RoundedRectView class useful, whether to use instances of directly or even to see how he makes them:

http://iphonedevelopment.blogspot.com/2008/11/creating-transparent-uiviews-rounded.html

Luke
  • 11,426
  • 43
  • 60
  • 69