准备知识:
CGContextRef context = UIGraphicsGetCurrentContext();可以获得图形上下文。
CGContextMoveToPoint、CGContextAddLineToPoint两个函数是构建描绘路径。
CGContextClosePath(context)函数是闭合描绘路径。
CGContextStrokePath函数是为闭合路径描边。
CGContextSetStrokeColorWithColor、[[UIColor blackColor] setStroke]两个函数设置描边的颜色。
CGContextSetFillColorWithColor、[[UIColor redColor] setFill]两个函数设置要填充的颜色。
CGContextDrawPath(context, kCGPathFillStroke);设置描绘路径方式。常用的还有:kCGPathFill和kCGPathStroke
不多说了,上代码:
TestView.h
#import <UIKit/UIKit.h>
@interface TestView : UIView
@end
TestView.m
#import "TestView.h"
@implementation TestView
- (void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
//(1)画一张图片
// [self drawAPictureWithRect:rect andCurrentContect:ctx];
//(2)画一个箭头
// [self drawAnArrayWithRect:rect andCurrentContect:ctx];
//(3)画一个矩形
[self drawARectangleWithRect:rect andCurrentContect:ctx];
CGContextSaveGState(ctx);
CGContextRestoreGState(ctx);
}
/**
* 画一张图片
*
* @param rect 函数中传过来的绘图区域
* @param ctx 函数中传过来的上下文
*/
- (void)drawAPictureWithRect:(CGRect)rect andCurrentContect:(CGContextRef)ctx
{
UIImage *img = [UIImage imageNamed:@"test"];
[img drawInRect:rect];
}
/**
* 画一个箭头
*
* @param rect 函数中传过来的绘图区域
* @param ctx 函数中传过来的上下文
*/
- (void)drawAnArrayWithRect:(CGRect)rect andCurrentContect:(CGContextRef)ctx
{
// 绘制箭杆部分
CGContextMoveToPoint(ctx, 100, 100);
CGContextAddLineToPoint(ctx, 100, 25);
CGContextSetLineWidth(ctx, 20);
CGContextStrokePath(ctx);
// 绘制箭头部分
CGContextMoveToPoint(ctx, 80, 25);
CGContextAddLineToPoint(ctx, 120, 25);
CGContextAddLineToPoint(ctx, 100, 0);
CGContextSetFillColorWithColor(ctx, [[UIColor redColor] CGColor]);
CGContextFillPath(ctx);
}
/**
* 画一个矩形
*
* @param rect 函数中传过来的绘图区域
* @param ctx 函数中传过来的上下文
*/
- (void)drawARectangleWithRect:(CGRect)rect andCurrentContect:(CGContextRef)ctx
{
CGContextSetLineWidth(ctx, 2.0f);
CGContextSetStrokeColorWithColor(ctx, [[UIColor orangeColor] CGColor]);
CGRect rectangleRect = CGRectMake(20, 20, 200, 100);
CGContextAddRect(ctx, rectangleRect);
CGContextStrokePath(ctx);
}
@end
ViewController.m
#import "ViewController.h"
#import "TestView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
TestView *textV = [[TestView alloc] init];
textV.frame = CGRectMake((self.view.frame.size.width-239)/2, 20, 239, 222);
textV.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:textV];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end