在iOS中,学会使用渐变色来设置一个视图的颜色比用图片要好一些。
可以到guithb上下载CRGradientLabel类来做需要的UILabel,我把该类的继承UILabel改为了UIVIew,这样就可以把任意的VIew的颜色设置为渐变色了。
文件:
CRGradientLabel.h
#import <UIKit/UIKit.h>
@interface CRGradientLabel :UIView
@property (nonatomic,strong) NSArray *gradientColors;
@end
CRGradientLabel.m文件
#import "CRGradientLabel.h"
@import CoreGraphics;
@interface CRGradientLabel ()
@end
@implementation CRGradientLabel
- (id)initWithFrame:(CGRect)frame
{
self = [superinitWithFrame:frame];
if (self) {
// Initialization code
}
returnself;
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context =UIGraphicsGetCurrentContext();
NSMutableArray *colors = [NSMutableArrayarrayWithCapacity:[self.gradientColorscount]];
[self.gradientColorsenumerateObjectsUsingBlock:^(id obj,NSUInteger idx, BOOL *stop) {
if ([objisKindOfClass:[UIColorclass]]) {
[colors addObject:(__bridgeid)[obj CGColor]];
} elseif (CFGetTypeID((__bridgevoid *)obj) == CGColorGetTypeID()) {
[colors addObject:obj];
} else {
@throw [NSExceptionexceptionWithName:@"CRGradientLabelError"
reason:@"Object in gradientColors array is not a UIColor or CGColorRef"
userInfo:NULL];
}
}];
CGContextSaveGState(context);
CGContextScaleCTM(context,1.0, -1.0);
CGContextTranslateCTM(context,0, -rect.size.height);
CGGradientRef gradient =CGGradientCreateWithColors(NULL, (__bridgeCFArrayRef)colors, NULL);
CGPoint startPoint =CGPointMake(CGRectGetMidX(rect),CGRectGetMinY(rect));
CGPoint endPoint =CGPointMake(CGRectGetMidX(rect),CGRectGetMaxY(rect));
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint,
kCGGradientDrawsAfterEndLocation |kCGGradientDrawsBeforeStartLocation);
CGGradientRelease(gradient);
CGContextRestoreGState(context);
[superdrawRect: rect];
}
@end
效果图:
使用的例子:
.m 文件:
导入CRGradientLabel头文件
#import "ViewController.h"
#import "CRGradientLabel.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
CRGradientLabel * view = [[CRGradientLabelalloc] initWithFrame:
CGRectMake(20,64,345,500)];
view.gradientColors =@[[UIColorcolorWithRed:239/255.0fgreen:77/255.0fblue:182/255.0falpha:1.0f], [UIColorcolorWithRed:198/255.0fgreen:67/255.0fblue:252/255.0falpha:1.0f]]; //该数组存放渐变色
[self.viewaddSubview:view];
}
@end