背景颜色渐变实现

项目名称:XDCalendarDemo-scroll

源码地址:https://github.com/xieyajie/XDCalendarDemo-scroll

用于控件:UIButton

类库引用:#import <QuartzCore/QuartzCore.h>

代码实现:

1、最开始使用以下方法,正确的实现了将button的背景颜色变成渐变色。但是在触发button点击事件时,背景不能变成在方法setBackgroundImage: forState:中设定好的图片。

1 - (void)gradientImageInRect:(CGRect)rect forView:(UIView *)view
2 {
3     CAGradientLayer *gradient = [CAGradientLayer layer];
4     gradient.frame = rect;
5     gradient.colors = [NSArray arrayWithObjects:(id)[UIColor redColor].CGColor, (id)[UIColor yellowColor].CGColor, (id)[UIColor greenColor].CGColor,nil];
6     [view.layer insertSublayer:gradient atIndex:0];
7 }

2、我需要的颜色R、G、B值都是相同的,选用这种方法,生成渐变色的image,在方法setBackgroundImage: forState:中设定image。

 1 /*
 2  *size:要生成图片的区域
 3  *start:颜色开始的值
 4  *end:颜色结束的值
 5  *centre:要绘制区域的中心点
 6  *radius:CGGradientDrawingOptions
 7  */
 8 - (UIImage *)radialGradientImage:(CGSize)size start:(float)start end:(float)end centre:(CGPoint)centre radius:(float)radius {
 9     // Initialise
10     UIGraphicsBeginImageContextWithOptions(size, YES, 1);
11     
12     // Create the gradient's colours
13     size_t num_locations = 2;
14     CGFloat locations[2] = { 0.0, 1.0 };
15     CGFloat components[8] = { start,start,start, 1.0,  // Start color
16         end,end,end, 1.0 }; // End color
17     
18     CGColorSpaceRef myColorspace = CGColorSpaceCreateDeviceRGB();
19     CGGradientRef myGradient = CGGradientCreateWithColorComponents (myColorspace, components, locations, num_locations);
20     
21     // Normalise the 0-1 ranged inputs to the width of the image
22     CGPoint myCentrePoint = CGPointMake(centre.x * size.width, centre.y * size.height);
23     float myRadius = MIN(size.width, size.height) * radius;
24     
25     // Draw
26     CGContextDrawRadialGradient (UIGraphicsGetCurrentContext(), myGradient, myCentrePoint,
27                                  0, myCentrePoint, myRadius,
28                                  kCGGradientDrawsAfterEndLocation);
29     
30     // Grab it as an autoreleased image
31     UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
32     
33     // Clean up
34     CGColorSpaceRelease(myColorspace); 
35     CGGradientRelease(myGradient); 
36     UIGraphicsEndImageContext();
37     return image;
38 }

3、如果R、G、B值各不相同,适当修改上面代码中的

CGFloat components[8] = { start,start,start, 1.0,  // Start color
         end,end,end, 1.0 };
posted @ 2013-04-18 12:59  dhcxyj  阅读(373)  评论(0编辑  收藏  举报