iOS模仿Solar滑动渐变色过渡效果gradient

一直很喜欢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或者其它方法会有更好的效果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值