一直很喜欢Solar的颜色变化效果,看了core graphic的知识后就自己动手试了下。Solar:https://itunes.apple.com/cn/app/solar-weather/id542875991?mt=8
实现方式非常简单,使用渐变色与touchesBegan/move/end 回调。
下面是UIView的代码,直接贴到viewController上就可以了。
#import "CTTView.h"
@interfaceCTTView()
{
UIColor *upsideColor;
UIColor *downsideColor;
CGPoint startPoint;
CGPoint curPoint;
}
@end
@implementation CTTView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [superinitWithFrame:frame];
if (self) {
[selfsetBackgroundColor:[UIColorwhiteColor]];
}
returnself;
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context =UIGraphicsGetCurrentContext();
CGColorSpaceRef colorSpace =CGColorSpaceCreateDeviceRGB();
float varY =fabs(curPoint.y -startPoint.y)/6;
//varY是手指move的距离算出的,是颜色变化的根据,下面的RGB色值可以随便改,但必须在0.0-1.0之间,如果超过1.0默认为1,RGB同时为1时就是一片白。
UIColor *topColor = [UIColorcolorWithRed:(0.22 +floor(varY)/100)green:0.56blue:0.23alpha:0.7];
UIColor *bottomColor = [UIColorcolorWithRed:0.22green:0.123blue:(1.0-floor(varY)/100)alpha:0.8];
//这个数组可以加多个颜色,布置渐变色时按照数组内颜色的顺序画
NSArray *colors =@[(__bridgeid)topColor.CGColor,(__bridgeid)bottomColor.CGColor];
//locations是对应上面colors每个color的位置,元素个数要和colors一样。如果locations里只有两个值,会默认改成0.0和1.0
constCGFloat locations[] = {0.0,1.0};
//创建渐变色
CGGradientRef gradient =CGGradientCreateWithColors(colorSpace, (__bridgeCFArrayRef)colors, locations);
CGPoint startPoint =CGPointMake([UIScreenmainScreen].bounds.size.width/2,0);
CGPoint endPoint =CGPointMake([UIScreenmainScreen].bounds.size.width/2, [UIScreen mainScreen].bounds.size.height);
//画渐变色,渐变色的渐变方向垂直于startPoint与endPoint的连线
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint,0);
//句柄,一定要释放
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
startPoint = [[touchesanyObject] locationInView:self];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
curPoint = [[touchesanyObject] locationInView:self];
[selfsetNeedsDisplay];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
curPoint =startPoint;
[selfsetNeedsDisplay];
}
@end
不断地调用setNeedsDisplay貌似会有效率问题,如果有更好的方法欢迎大牛们告诉我,非常感谢!
这个并不是很完善,日后会再往里加东西。我觉得solar本身可能也不是用这种方法实现的,也许用cocos2d或者其它方法会有更好的效果。