免费开源的iOS开发学习平台

绘图CoreGraphics:4-常见图形的绘制方法

本节我们通过一些实际的例子来学习下,如何使用CoreGraphics框架来对视图样式进行绘制,包括绘制直线、矩形和椭圆形。

准备工作

使用CoreGraphics框架是针对视图对象进行绘制,因此,我们需要首先新建一个自定义视图类,继承自UIView

在storyboard中,设置主控制器的View为MYView类

在MYView.m中,添加drawRect:方法,在该方法中添加绘图相关的代码

#import "MYView.h"

@implementation MYView

- (void)drawRect:(CGRect)rect {
    // 编写绘图方法
}

@end

绘制直线

假如需要绘制直线,需要创建一个贝塞尔路径对象,并指定路径的开始点和结束点,然后在开始点和结束点之间添加一条连线。

- (void)drawRect:(CGRect)rect {
    //获取上下文/环境
    CGContextRef context = UIGraphicsGetCurrentContext();
    //设置画笔宽度
    CGContextSetLineWidth(context, 3.0);
    //设置画笔颜色
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    
    //绘图
    //创建绘图路径
    UIBezierPath *path = [UIBezierPath bezierPath];
    //设置起始点
    [path moveToPoint:CGPointZero];
    [path addLineToPoint:CGPointMake(200, 200)];
    //添加到上下文
    CGContextAddPath(context, path.CGPath);
    //渲染上下文
    CGContextStrokePath(context);
}

运行结果。

绘制矩形

当绘制矩形时,可以使用使用贝塞尔路径的bezierPathWithRect:方法,传入一个矩形的frame,然后渲染到屏幕上。

- (void)drawRect:(CGRect)rect {
    //获取上下文/环境
    CGContextRef context = UIGraphicsGetCurrentContext();
    //设置画笔宽度
    CGContextSetLineWidth(context, 3.0);
    //设置画笔颜色
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    
    //绘图
    //设置矩形的位置和大小
    CGRect myRect = CGRectMake(50, 50, 100, 100);
    //创建绘图路径
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:myRect];
    //添加到上下文
    CGContextAddPath(context, path.CGPath);
    //渲染上下文
    CGContextStrokePath(context);

}

运行结果。

绘制圆形/椭圆形

对于圆形和椭圆形的绘制方法也非常简单,在初始化贝塞尔路径时,调用bezierPathWithOvalInRect:方法,并传入一个指定的矩形区域,就可以得到一个充满该矩形区域的圆形或椭圆形。

- (void)drawRect:(CGRect)rect {
    //获取上下文/环境
    CGContextRef context = UIGraphicsGetCurrentContext();
    //设置画笔宽度
    CGContextSetLineWidth(context, 3.0);
    //设置画笔颜色
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    
    //绘图
    //设置矩形的位置和大小
    CGRect myRect = CGRectMake(50, 50, 200, 100);
    //创建绘图路径
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:myRect];
    //添加到上下文
    CGContextAddPath(context, path.CGPath);
    //渲染上下文
    CGContextStrokePath(context);
}

运行结果。

示例代码

https://github.com/99ios/14.1.4