專案中偶爾會遇到cell背景漸變或者view背景漸變的介面需求,偷懶解決的方法就是讓UI妹紙給切個圖拿來就用。但是如果專案中需要的漸變色比較多的話,顯然切圖是很不合適的,也容易使得專案的體積冗餘。
- (void)drawRect:(CGRect)rect {
// Drawing code
CGContextRef context = UIGraphicsGetCurrentContext();
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
// 建立起點的顏色
CGColorRef beginColor = CGColorCreate(colorSpaceRef, (CGFloat[]){1.0f,1.0f,1.0f,1.0f});
CGColorRef endColor = CGColorCreate(colorSpaceRef, (CGFloat[]){0.83f, 0.83f, 0.83f, 1.0f});
CGRect paperRect = self.bounds;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat locations[] = {0.0,1.0};
NSArray *colors = [NSArray arrayWithObjects:(__bridge id)beginColor,(__bridge id)endColor, nil];
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)CFBridgingRetain(colors), locations);
CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
CGContextSaveGState(context);
CGContextAddRect(context, rect);
CGContextClip(context);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGContextRestoreGState(context);
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
// add line stroke
CGRect strokeRect = CGRectInset(paperRect, 5.0, 5.0);
CGColorRef lineColor = CGColorCreate(colorSpaceRef, (CGFloat[]){0.81,0.43,0.99,1.0f});
CGContextSetStrokeColorWithColor(context, lineColor);
CGContextSetLineWidth(context, 0.5);
CGContextStrokeRect(context, strokeRect);
}
複製程式碼
- 然後將
cell.backgroundView
設定為我們建立的漸變View就可以了。
- 還有一個漸變的寫法,匯入類庫quartcore並#import <QuartzCore/QuartzCore.h>,這個就不屬於在context上畫,而是將圖層插入到view層上面。那麼這裡就涉及到Quartz Core 圖層程式設計了。
CAGradientLayer *_gradientLayer = [CAGradientLayer layer];
_gradientLayer.bounds = cell.contentView.bounds;
_gradientLayer.borderWidth = 0;
_gradientLayer.frame = cell.contentView.bounds;
_gradientLayer.colors = [NSArray arrayWithObjects:
(id)[[UIColor clearColor] CGColor],
(id)[[UIColor blackColor] CGColor],nil];
_gradientLayer.startPoint = CGPointMake(0.5, 0.5);
_gradientLayer.endPoint = CGPointMake(0.5, 1.0);
[cell.contentView.layer insertSublayer:_gradientLayer atIndex:0];
複製程式碼