易采站长站为您分析iOS App开发中用CGContextRef绘制基本图形的基本示例,CGContextRef同时可以进行图形颜色的填充以及文字的书写,需要的朋友可以参考下
#import <QuartzCore/QuartzCore.h>
覆盖DranRect方法,在此方法中绘制图形。
CustomView写好之后,需要使用到视图控制器中。
使用方法:
复制代码
CustomView *customView = [[CustomView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[self.view addSubview:customView];
- (void)drawRect:(CGRect)rect
{
//获得当前画板
CGContextRef ctx = UIGraphicsGetCurrentContext();
//颜色
CGContextSetRGBStrokeColor(ctx, 0.2, 0.2, 0.2, 1.0);
//画线的宽度
CGContextSetLineWidth(ctx, 0.25);
//开始写字
[@"我是文字" drawInRect:CGRectMake(10, 10, 100, 30) withFont:font];
[super drawRect:rect];
}
这段代码就可以很漂亮的写出四个大字:我是文字。很容易理解,每句话都有注释。
- (void)drawRect:(CGRect)rect
{
//获得当前画板
CGContextRef ctx = UIGraphicsGetCurrentContext();
//颜色
CGContextSetRGBStrokeColor(ctx, 0.2, 0.2, 0.2, 1.0);
//画线的宽度
CGContextSetLineWidth(ctx, 0.25);
//顶部横线
CGContextMoveToPoint(ctx, 0, 10);
CGContextAddLineToPoint(ctx, self.bounds.size.width, 10);
CGContextStrokePath(ctx);
[super drawRect:rect];
}
Graphics Context是图形上下文,也可以理解为一块画布,我们可以在上面进行绘画操作,绘制完成后,将画布放到我们的view中显示即可,view看作是一个画框.
CGContextRef功能强大,我们借助它可以画各种图形。开发过程中灵活运用这些技巧,可以帮助我们提供代码水平。
首先创建一个集成自UIView的,自定义CustomView类。
在CustomView.m中实现代码。
#import <QuartzCore/QuartzCore.h>
覆盖DranRect方法,在此方法中绘制图形。
CustomView写好之后,需要使用到视图控制器中。
使用方法:
复制代码
CustomView *customView = [[CustomView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[self.view addSubview:customView];
写文字
复制代码- (void)drawRect:(CGRect)rect
{
//获得当前画板
CGContextRef ctx = UIGraphicsGetCurrentContext();
//颜色
CGContextSetRGBStrokeColor(ctx, 0.2, 0.2, 0.2, 1.0);
//画线的宽度
CGContextSetLineWidth(ctx, 0.25);
//开始写字
[@"我是文字" drawInRect:CGRectMake(10, 10, 100, 30) withFont:font];
[super drawRect:rect];
}
这段代码就可以很漂亮的写出四个大字:我是文字。很容易理解,每句话都有注释。
画直线
复制代码- (void)drawRect:(CGRect)rect
{
//获得当前画板
CGContextRef ctx = UIGraphicsGetCurrentContext();
//颜色
CGContextSetRGBStrokeColor(ctx, 0.2, 0.2, 0.2, 1.0);
//画线的宽度
CGContextSetLineWidth(ctx, 0.25);
//顶部横线
CGContextMoveToPoint(ctx, 0, 10);
CGContextAddLineToPoint(ctx, self.bounds.size.width, 10);
CGContextStrokePath(ctx);
[super drawRect:rect];
}










