iOS 图形处理 翻译
* 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; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。