
* Core Graphics(任何以CG开头的类) * 在drawRect方法里,甚至是空方法实现 * 所有shouldRasterize属性是YES的CALayers对象 * 所有用了masks(setMasksToBounds)和动态阴影的(setShadow*)的CALayers对象 * 所有文字的绘制,包括CoreText * Group opacity(UIViewGroupOpacity)




// In CBHybrid.m #import "CBHybrid.h" @implementation CBHybrid // Resizable background image for normal state static UIImage *gBackgroundImage; // Resizable background image for highlighted state static UIImage *gBackgroundImageHighlighted; // Background image border radius and height static int borderRadius = 5; static int height = 37;
- (UIImage *)drawBackgroundImageHighlighted:(BOOL)highlighted {
// Drawing code goes here
}
float width = 1 + (borderRadius * 2);
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, 0.0); CGContextRef context = UIGraphicsGetCurrentContext(); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// Gradient Declarations // NSArray *gradientColors = ... // Draw rounded rectangle bezier path UIBezierPath *roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(0, 0, width, height) cornerRadius: borderRadius]; // Use the bezier as a clipping path [roundedRectanglePath addClip]; // Use one of the two gradients depending on the state of the button CGGradientRef background = highlighted? highlightedGradient : gradient; // Draw gradient within the path CGContextDrawLinearGradient(context, background, CGPointMake(140, 0), CGPointMake(140, height-1), 0); // Draw border // [borderColor setStroke... // Draw Inner Glow // UIBezierPath *innerGlowRect...
我们唯一需要添加的步骤就是,用UIGraphicsEndImageContext来保存图像信息,并且放到UIImage对象中。
UIImage* backgroundImage = UIGraphicsGetImageFromCurrentImageContext(); // Cleanup UIGraphicsEndImageContext();
- (void)setupBackgrounds {
// Generate background images if necessary
if (!gBackgroundImage &&!gBackgroundImageHighlighted) {
gBackgroundImage = [[self drawBackgroundImageHighlighted:NO] resizableImageWithCapInsets:UIEdgeInsetsMake(borderRadius, borderRadius, borderRadius, borderRadius) resizingMode:UIImageResizingModeStretch];
gBackgroundImageHighlighted = [[self drawBackgroundImageHighlighted:YES] resizableImageWithCapInsets:UIEdgeInsetsMake(borderRadius, borderRadius, borderRadius, borderRadius) resizingMode:UIImageResizingModeStretch];
}
// Set background for the button instance
[self setBackgroundImage:gBackgroundImage forState:UIControlStateNormal];
[self setBackgroundImage:gBackgroundImageHighlighted forState:UIControlStateHighlighted];
}
+ (CBHybrid *)buttonWithType:(UIButtonType)type
{
return [super buttonWithType:UIButtonTypeCustom];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
[self setupBackgrounds];
return self;
}

原文:http://blog.csdn.net/sqc3375177/article/details/23300365