Skip to content

Instantly share code, notes, and snippets.

@linktoming
Forked from digerata/RoundedRectLabel.h
Created October 30, 2012 08:57
Show Gist options
  • Save linktoming/3979111 to your computer and use it in GitHub Desktop.
Save linktoming/3979111 to your computer and use it in GitHub Desktop.
Create a UILabel with a rounded rect background like in the iPhone Mail app. (Much faster than using UILabel.layer.cornerRadius)
//
// RoundedRectLabel.h
//
#import <UIKit/UIKit.h>
@interface CountLabel : UILabel {
NSInteger cornerRadius;
UIColor *rectColor;
}
@property (nonatomic) NSInteger cornerRadius;
@property (nonatomic, retain) UIColor *rectColor;
- (void) setBackgroundColor:(UIColor *)color;
- (void) drawRoundedRect:(CGContextRef)c rect:(CGRect)rect radius:(int)corner_radius color:(UIColor *)color;
@end
//
// RoundedRectLabel.m
//
#import "RoundedRectLabel.h"
#import <QuartzCore/QuartzCore.h>
@implementation CountLabel
@synthesize cornerRadius;
@synthesize rectColor;
- (void)dealloc {
[rectColor release];
[super dealloc];
}
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
// Initialization code
}
return self;
}
- (void) setBackgroundColor:(UIColor *)color
{
self.rectColor = color;
[super setBackgroundColor:[UIColor clearColor]];
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
if(cornerRadius == 0)
self.cornerRadius = 4;
[self drawRoundedRect:context rect:rect radius:cornerRadius color:rectColor];
[super drawRect:rect];
}
- (void) drawRoundedRect:(CGContextRef)c rect:(CGRect)rect radius:(int)corner_radius color:(UIColor *)color
{
int x_left = rect.origin.x;
int x_left_center = rect.origin.x + corner_radius;
int x_right_center = rect.origin.x + rect.size.width - corner_radius;
int x_right = rect.origin.x + rect.size.width;
int y_top = rect.origin.y;
int y_top_center = rect.origin.y + corner_radius;
int y_bottom_center = rect.origin.y + rect.size.height - corner_radius;
int y_bottom = rect.origin.y + rect.size.height;
/* Begin! */
CGContextBeginPath(c);
CGContextMoveToPoint(c, x_left, y_top_center);
/* First corner */
CGContextAddArcToPoint(c, x_left, y_top, x_left_center, y_top, corner_radius);
CGContextAddLineToPoint(c, x_right_center, y_top);
/* Second corner */
CGContextAddArcToPoint(c, x_right, y_top, x_right, y_top_center, corner_radius);
CGContextAddLineToPoint(c, x_right, y_bottom_center);
/* Third corner */
CGContextAddArcToPoint(c, x_right, y_bottom, x_right_center, y_bottom, corner_radius);
CGContextAddLineToPoint(c, x_left_center, y_bottom);
/* Fourth corner */
CGContextAddArcToPoint(c, x_left, y_bottom, x_left, y_bottom_center, corner_radius);
CGContextAddLineToPoint(c, x_left, y_top_center);
/* Done */
CGContextClosePath(c);
CGContextSetFillColorWithColor(c, color.CGColor);
CGContextFillPath(c);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment