标签:
效果如下:
ViewController.h
1 #import <UIKit/UIKit.h> 2 3 @interface ViewController : UIViewController 4 @end
ViewController.m
1 #import "ViewController.h" 2 #import "KMTriangleView.h" 3 4 @interface ViewController () 5 - (void)layoutUI; 6 @end 7 8 @implementation ViewController 9 10 - (void)viewDidLoad { 11 [super viewDidLoad]; 12 13 [self layoutUI]; 14 } 15 16 - (void)didReceiveMemoryWarning { 17 [super didReceiveMemoryWarning]; 18 // Dispose of any resources that can be recreated. 19 } 20 21 - (void)layoutUI { 22 KMTriangleView *triangleView = [[KMTriangleView alloc] initWithFrame:self.view.frame]; 23 self.view = triangleView; 24 } 25 26 @end
KMTriangleView.h
1 #import <UIKit/UIKit.h> 2 3 @interface KMTriangleView : UIView 4 @property CGPoint firstPoint; 5 @property CGPoint secondPoint; 6 @property CGPoint thirdPoint; 7 @property NSMutableArray *mArrPoint; 8 9 @end
KMTriangleView.m
1 #import "KMTriangleView.h" 2 3 @implementation KMTriangleView 4 #define kPointCount 3 5 6 - (id)initWithFrame:(CGRect)frame { 7 if (self = [super initWithFrame:frame]) { 8 self.backgroundColor = [UIColor whiteColor]; 9 UILabel *lblMsg = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, self.frame.size.width, 40)]; 10 lblMsg.text = @"任意点击屏幕内的3点以确定一个三角形"; 11 [self addSubview:lblMsg]; 12 13 _mArrPoint = [[NSMutableArray alloc] initWithCapacity:kPointCount]; 14 } 15 return self; 16 } 17 18 - (void)drawRect:(CGRect)rect { 19 CGContextRef contextRef = UIGraphicsGetCurrentContext(); //获取绘制上下文对象实例 20 CGContextSetRGBStrokeColor(contextRef, 0.5, 0.5, 0.5, 1.0); //设置笔画颜色 21 CGContextSetLineWidth(contextRef, 2.0); //设置线条粗细大小 22 CGPoint points[] = { _firstPoint, _secondPoint, _thirdPoint, _firstPoint }; 23 CGContextAddLines(contextRef, points, kPointCount+1); //设置线条的连接端点 24 CGContextStrokePath(contextRef); //沿着要求的路径,开始绘制 25 } 26 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 27 UITouch *touch = [touches anyObject]; 28 CGPoint touchPoint = [touch locationInView:self]; 29 [_mArrPoint addObject:[NSValue valueWithCGPoint:touchPoint]]; 30 31 if (_mArrPoint.count > 3) { 32 [_mArrPoint removeObjectAtIndex:0]; 33 } 34 if (_mArrPoint.count == 3) { 35 _firstPoint = [_mArrPoint[0] CGPointValue]; 36 _secondPoint = [_mArrPoint[1] CGPointValue]; 37 _thirdPoint = [_mArrPoint[2] CGPointValue]; 38 } 39 [self setNeedsDisplay]; //设置触发drawRect方法重新绘制内容;这句很关键,如不使用就不会触发drawRect方法 40 } 41 42 @end
标签:
原文地址:http://www.cnblogs.com/huangjianwu/p/4583990.html