forked from tylerneylon/moriarty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLineView.m
103 lines (75 loc) · 2.13 KB
/
LineView.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//
// LineView.m
// MadTiles
//
// Created by Tyler Neylon on 4/5/11.
// Copyright 2011 Bynomial. All rights reserved.
//
#import "LineView.h"
#import "NSObject+Be.h"
#import "UIView+Position.h"
#define kPadding 10
static float min(float a, float b) {
return (a < b ? a : b);
}
static float max(float a, float b) {
return (a < b ? b : a);
}
@interface LineView ()
- (void)drawWithOffset:(CGPoint)offset;
@end
@implementation LineView
@synthesize color, lineWidth;
- (id)initFromPoint:(CGPoint)a_ toPoint:(CGPoint)b_ {
CGRect frame = CGRectMake(min(a_.x, b_.x) - kPadding, min(a_.y, b_.y) - kPadding,
max(a_.x, b_.x) + 2 * kPadding, max(a_.y, b_.y) + 2 * kPadding);
if (![super initWithFrame:frame]) return nil;
a = a_;
b = b_;
self.color = [UIColor blackColor];
self.backgroundColor = [UIColor clearColor];
self.userInteractionEnabled = NO;
lineWidth = 2;
return self;
}
- (void)dealloc {
self.color = nil;
[super dealloc];
}
+ (LineView *)lineFromPoint:(CGPoint)a toPoint:(CGPoint)b {
return [[LineView be] initFromPoint:a toPoint:b];
}
- (UIImage *)getImage {
CGSize imageSize = CGSizeMake(self.frameRight, self.frameBottom);
UIGraphicsBeginImageContext(imageSize);
[self drawWithOffset:CGPointZero];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
- (void)setColor:(UIColor *)newColor {
if (color == newColor) return;
[color release];
color = [newColor retain];
[self setNeedsDisplay];
}
- (void)setLineWidth:(CGFloat)newLineWidth {
if (lineWidth == newLineWidth) return;
lineWidth = newLineWidth;
[self setNeedsDisplay];
}
#pragma mark UIView methods
- (void)drawRect:(CGRect)rect {
[self drawWithOffset:self.frameOrigin];
}
#pragma mark private methods
- (void)drawWithOffset:(CGPoint)offset {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(ctx, lineWidth);
[color setStroke];
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, a.x - offset.x, a.y - offset.y);
CGContextAddLineToPoint(ctx, b.x - offset.x, b.y - offset.y);
CGContextStrokePath(ctx);
}
@end