摘要 : CGContextRef 功能强大,我们借助它可以画各种图形。这里所举例子只是简单内容绘制,冰山一角,对此感兴趣的朋友可以举一反三,实现各种酷炫效果。

效果如下:

使用 CGContextRef 进行简单内容绘制-LMLPHP

KMDrawView.h

 #import <UIKit/UIKit.h>

 @interface KMDrawView : UIView

 @end

KMDrawView.m

 #import "KMDrawView.h"

 @interface KMDrawView ()
- (void)drawFont;
- (void)drawLine;
- (void)drawCircle;
- (void)drawRectangle; @end @implementation KMDrawView - (instancetype)initWithFrame:(CGRect)frame{
if (self=[super initWithFrame:frame]) {
self.backgroundColor = [UIColor colorWithWhite:0.7 alpha:1.0];
}
return self;
} - (void)drawRect:(CGRect)rect {
[self drawFont];
[self drawLine];
[self drawCircle];
[self drawRectangle]; [super drawRect:rect];
} #pragma mark - 绘制『文字』、『线条』、『圆形』、『矩形』
- (void)drawFont {
NSDictionary *dicAttribute = @{
NSForegroundColorAttributeName : [UIColor brownColor],
NSFontAttributeName : [UIFont systemFontOfSize:18.0]
}; [@"我是文字" drawInRect:CGRectMake(20.0, 20.0, 100.0, 30.0) withAttributes:dicAttribute];
} - (void)drawLine {
CGContextRef contextRef = UIGraphicsGetCurrentContext(); //获取绘制上下文对象实例
CGContextSetRGBStrokeColor(contextRef, 0.5, 0.5, 0.5, 1.0); //设置笔画颜色
CGContextSetLineWidth(contextRef, 2.0); //设置线条粗细大小 CGContextMoveToPoint(contextRef, 20.0, 100.0); //设置直线的首端
CGContextAddLineToPoint(contextRef, 320.0, 100.0); //设置直线的末端
CGContextStrokePath(contextRef); //沿着要求的路径,开始绘制
} - (void)drawCircle {
CGContextRef contextRef = UIGraphicsGetCurrentContext(); //获取绘制上下文对象实例
CGContextSetRGBStrokeColor(contextRef, 1.0, 1.0, 1.0, 1.0); //设置笔画颜色
CGContextSetLineWidth(contextRef, 2.0); //设置线条粗细大小 //voidCGContextAddArc(CGContextRef c,CGFloat x,CGFloat y,CGFloat radius,CGFloat startAngle,CGFloat endAngle,int clockwise)
//1弧度=180°/π(≈57.3°)度
//360°=360 * π/180=2π弧度
//x,y为圆点坐标,radius半径,startAngle为开始的弧度,endAngle为结束的弧度,clockwise0为顺时针,1为逆时针。
CGContextAddArc(contextRef, 70.0, 200.0, 50.0, , *M_PI, ); //添加一个圆;M_PI为180度
CGContextDrawPath(contextRef, kCGPathStroke); //绘制路径
} - (void)drawRectangle {
CGContextRef contextRef = UIGraphicsGetCurrentContext(); //获取绘制上下文对象实例
CGContextSetRGBStrokeColor(contextRef, 0.0, 0.0, 0.0, 1.0); //设置笔画颜色
CGContextSetLineWidth(contextRef, 2.0); //设置线条粗细大小 CGContextAddRect(contextRef, CGRectMake(20.0, 300.0, 200.0, 100.0)); //设置矩形位置和宽高
CGContextStrokePath(contextRef); //沿着要求的路径,开始绘制
} @end

ViewController.h

 #import <UIKit/UIKit.h>

 @interface ViewController : UIViewController

 @end

ViewController.m

 #import "ViewController.h"
#import "KMDrawView.h" @interface ViewController ()
- (void)layoutUI;
@end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; [self layoutUI];
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} - (void)layoutUI {
KMDrawView *drawView = [[KMDrawView alloc] initWithFrame:self.view.frame];
[self.view addSubview:drawView];
} @end
04-26 07:18