MST

星途 面试题库

面试题:Objective-C中Core Graphics绘制简单图形

在Objective-C项目中,使用Core Graphics框架绘制一个填充红色的圆形,圆心在视图中心,半径为50,简述关键代码步骤并给出实现代码。
39.8万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试

关键代码步骤:

  1. 获取视图的图形上下文。
  2. 设置填充颜色为红色。
  3. 计算圆心位置。
  4. 使用CGContextAddArc方法添加圆形路径。
  5. 使用CGContextFillPath方法填充路径。

实现代码:

#import "ViewController.h"

@implementation ViewController

- (void)drawRect:(CGRect)rect {
    // 获取当前图形上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // 设置填充颜色为红色
    CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
    
    // 计算圆心位置
    CGFloat centerX = CGRectGetMidX(rect);
    CGFloat centerY = CGRectGetMidY(rect);
    CGFloat radius = 50;
    
    // 添加圆形路径
    CGContextAddArc(context, centerX, centerY, radius, 0, 2 * M_PI, 0);
    
    // 填充路径
    CGContextFillPath(context);
}

@end