实现思路
- 创建自定义视图:继承自
UIView
,并重写drawRect:
方法来进行图形绘制。
- 绘制贝塞尔曲线组成的闭合路径:使用
UIBezierPath
类来创建和管理贝塞尔曲线,通过添加多个曲线段并闭合路径。
- 渐变填充:使用
CAGradientLayer
来实现渐变效果,并将其添加到自定义视图的layer
上。
- 动画效果:使用
CABasicAnimation
来实现填充颜色在3秒内从蓝色渐变为绿色的动画。
核心代码
- 自定义视图类
#import <UIKit/UIKit.h>
@interface CustomView : UIView
@end
#import "CustomView.h"
#import <QuartzCore/QuartzCore.h>
@implementation CustomView
- (void)drawRect:(CGRect)rect {
// 创建贝塞尔路径
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(100, 100)];
[path addCurveToPoint:CGPointMake(200, 200) controlPoint1:CGPointMake(120, 150) controlPoint2:CGPointMake(180, 150)];
[path addCurveToPoint:CGPointMake(100, 300) controlPoint1:CGPointMake(220, 250) controlPoint2:CGPointMake(80, 250)];
[path closePath];
// 创建渐变层
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = self.bounds;
gradientLayer.colors = @[(id)[UIColor blueColor].CGColor, (id)[UIColor greenColor].CGColor];
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(1, 1);
gradientLayer.mask = [CAShapeLayer layer];
[(CAShapeLayer *)gradientLayer.mask setPath:path.CGPath];
[self.layer addSublayer:gradientLayer];
// 添加动画
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"colors"];
animation.fromValue = @[(id)[UIColor blueColor].CGColor];
animation.toValue = @[(id)[UIColor greenColor].CGColor];
animation.duration = 3.0;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[gradientLayer addAnimation:animation forKey:@"colorChange"];
}
@end
- 在视图控制器中使用自定义视图
#import "ViewController.h"
#import "CustomView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
CustomView *customView = [[CustomView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:customView];
}
@end