MST
星途 面试题库

面试题:Objective-C里Core Graphics的复杂路径绘制与动画

使用Objective-C和Core Graphics创建一个自定义视图,绘制一个由多条贝塞尔曲线组成的复杂闭合路径,并对该路径进行渐变填充。另外,实现一个动画效果,使路径的填充颜色在3秒内从蓝色渐变为绿色,说明实现思路及核心代码。
17.0万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 创建自定义视图:继承自UIView,并重写drawRect:方法来进行图形绘制。
  2. 绘制贝塞尔曲线组成的闭合路径:使用UIBezierPath类来创建和管理贝塞尔曲线,通过添加多个曲线段并闭合路径。
  3. 渐变填充:使用CAGradientLayer来实现渐变效果,并将其添加到自定义视图的layer上。
  4. 动画效果:使用CABasicAnimation来实现填充颜色在3秒内从蓝色渐变为绿色的动画。

核心代码

  1. 自定义视图类
#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
  1. 在视图控制器中使用自定义视图
#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