-
Notifications
You must be signed in to change notification settings - Fork 21
/
IOSKnobControl.m
2233 lines (1870 loc) · 78.3 KB
/
IOSKnobControl.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
iOS Knob Control
Copyright (c) 2013-14, Jimmy Dee
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <CoreText/CoreText.h>
#import "IOSKnobControl.h"
/*
* Return animations rotate through this many radians per second when self.timeScale == 1.0.
*/
#define IKC_ANGULAR_VELOCITY_AT_UNIT_TIME_SCALE 0.52359878163217 // M_PI/6.0 rad/s
// 1,000 RPM, faster than a finger can reasonably rotate the knob. see comments in followGestureToPosition:duration:
#define IKC_FAST_ANGULAR_VELOCITY (200.0 * IKC_ANGULAR_VELOCITY_AT_UNIT_TIME_SCALE)
/*
* Rotary dial animations are 10 times faster.
*/
#define IKC_ROTARY_DIAL_ANGULAR_VELOCITY_AT_UNIT_TIME_SCALE 5.2359878163217 // 5.0*M_PI/3.0 rad/s
#define IKC_EPSILON 1e-7
// this should probably be IKC_MIN_FINGER_HOLE_RADIUS. the actual radius should be a property initialized to this value, and this min. value should be enforced.
// but I'm reluctant to introduce a new property just for rotary dial mode, and I'm not sure whether it's really necessary. it would only be useful for very
// large dials (on an iPad).
#define IKC_DEFAULT_FINGER_HOLE_RADIUS 22.0
#define IKC_TITLE_MARGIN_RATIO 0.2
// Must match IKC_VERSION and IKC_BUILD from IOSKnobControl.h.
#define IKC_TARGET_VERSION 0x010400
#define IKC_TARGET_BUILD 1
#if IKC_TARGET_VERSION != IKC_VERSION || IKC_TARGET_BUILD != IKC_BUILD
#error IOSKnobControl.h version and build do not match IOSKnobControl.m.
#endif // target version/build check
static int numberDialed(float position) {
// normalize position to [0, 2*M_PI)
while (position < 0) position += 2.0*M_PI;
while (position >= 2.0*M_PI) position -= 2.0*M_PI;
// now number is in [0, 11]
int number = position * 6.0 / M_PI;
// this is not 0 but the dead spot clockwise from 1
if (number == 0) return 12;
// this is the next dead spot, counterclockwise from 0
if (number == 11) return 11;
// now number is in [1, 10]. the modulus makes 1..10 into 1..9, 0.
// the return value is in [0, 9].
return number % 10;
}
// DEBT: Doesn't account for variable _fingerHoleMargin
static CGRect adjustFrame(CGRect frame, CGFloat fingerHoleRadius) {
const float IKC_MINIMUM_DIMENSION = ceil(9.72 * fingerHoleRadius);
if (frame.size.width < IKC_MINIMUM_DIMENSION) frame.size.width = IKC_MINIMUM_DIMENSION;
if (frame.size.height < IKC_MINIMUM_DIMENSION) frame.size.height = IKC_MINIMUM_DIMENSION;
// force the frame to be square. choose the larger of the two dimensions as the square side in case it's not.
float side = MAX(frame.size.width, frame.size.height);
frame.size.width = frame.size.height = side;
return frame;
}
#pragma mark - String deprecation wrapper
@protocol NSStringDeprecatedMethods
- (CGSize)sizeWithFont:(UIFont*)font;
@end
@interface NSString(IKC)
- (CGSize)sizeOfTextWithFont:(UIFont*)font;
@end
@implementation NSString(IKC)
/*
* For portability among iOS versions.
*/
- (CGSize)sizeOfTextWithFont:(UIFont*)font
{
CGSize textSize;
if ([self respondsToSelector:@selector(sizeWithAttributes:)]) {
// iOS 7+
textSize = [self sizeWithAttributes:@{NSFontAttributeName: font}];
}
else {
// iOS 5 & 6
// following http://vgable.com/blog/2009/06/15/ignoring-just-one-deprecated-warning/
id<NSStringDeprecatedMethods> string = (id<NSStringDeprecatedMethods>)self;
textSize = [string sizeWithFont:font];
}
return textSize;
}
@end
#pragma mark - IKCTextLayer interface
/**
* Custom text layer. Looks much better than CATextLayer. Destined for the Violation framework.
*/
@interface IKCTextLayer : CALayer
@property (nonatomic, copy) NSString* fontName;
@property (nonatomic) CGFloat fontSize;
@property (nonatomic) CGColorRef foregroundColor;
@property (nonatomic, copy) id string;
@property (nonatomic) CGFloat horizMargin, vertMargin;
@property (nonatomic) BOOL adjustsFontSizeForAttributed;
@property (nonatomic, readonly) BOOL ignoringForegroundColor;
@property (nonatomic, readonly) BOOL ignoringFontName;
@property (nonatomic, readonly) BOOL ignoringFontSize;
@property (nonatomic, readonly) CFAttributedStringRef attributedString;
+ (instancetype)layer;
@end
#pragma mark - IKCTextLayer implementation
@implementation IKCTextLayer
+ (instancetype)layer
{
return [[self alloc] init];
}
- (instancetype)init
{
self = [super init];
if (self) {
_fontSize = 0.0;
_foregroundColor = [UIColor blackColor].CGColor;
CFRetain(_foregroundColor);
_horizMargin = _vertMargin = 0.0;
_adjustsFontSizeForAttributed = NO;
_ignoringForegroundColor = NO;
_ignoringFontName = _ignoringFontSize = NO;
self.opaque = NO;
self.backgroundColor = [UIColor clearColor].CGColor;
[self setNeedsDisplay];
}
return self;
}
- (void)dealloc
{
if (_foregroundColor) CFRelease(_foregroundColor);
}
- (void)setHorizMargin:(CGFloat)horizMargin
{
if (_horizMargin != horizMargin) [self setNeedsDisplay];
_horizMargin = horizMargin;
}
- (void)setVertMargin:(CGFloat)vertMargin
{
if (_vertMargin != vertMargin) [self setNeedsDisplay];
_vertMargin = vertMargin;
}
- (void)setString:(id)string
{
BOOL currentIsAttributed = [_string isKindOfClass:NSAttributedString.class];
BOOL newIsAttributed = [string isKindOfClass:NSAttributedString.class];
if (currentIsAttributed != newIsAttributed) {
[self setNeedsDisplay];
}
else if (currentIsAttributed) {
NSAttributedString* currentValue = _string;
NSAttributedString* newValue = string;
if (![currentValue isEqualToAttributedString:newValue]) {
[self setNeedsDisplay];
}
}
else {
NSString* currentValue = _string;
NSString* newValue = string;
if (![currentValue isEqualToString:newValue]) {
[self setNeedsDisplay];
}
}
_string = string;
}
- (void)setFontName:(NSString *)fontName
{
if (!_ignoringFontName && ![_fontName isEqualToString:fontName]) [self setNeedsDisplay];
_fontName = fontName;
}
- (void)setFontSize:(CGFloat)fontSize
{
if (!_ignoringFontSize && _fontSize != fontSize) [self setNeedsDisplay];
_fontSize = fontSize;
}
- (void)setAdjustsFontSizeForAttributed:(BOOL)adjustsFontSizeForAttributed
{
if ([_string isKindOfClass:NSAttributedString.class] && _adjustsFontSizeForAttributed != adjustsFontSizeForAttributed) {
[self setNeedsDisplay];
}
_adjustsFontSizeForAttributed = adjustsFontSizeForAttributed;
}
- (void)setForegroundColor:(CGColorRef)foregroundColor
{
if (!foregroundColor) return;
// _ignoringForegroundColor is set if the input is an attributed string with a specified
// foreground color attribute. in that case, we don't need to redraw when this method
// is called.
// DEBT: Also set _ignoring when there's no title color change from the previous state
// to the current one?
if (!_ignoringForegroundColor && !CGColorEqualToColor(foregroundColor, _foregroundColor)) {
[self setNeedsDisplay];
}
if (_foregroundColor) CFRelease(_foregroundColor);
_foregroundColor = foregroundColor;
CFRetain(_foregroundColor);
}
- (void)display
{
/*
* Scale params for display resolution.
*/
CGSize size = self.bounds.size;
CGFloat horizMargin = _horizMargin;
CGFloat vertMargin = _vertMargin;
/*
* Get the attributed string to render
*/
CFAttributedStringRef attributed = self.attributedString;
// the font used by the attributed string
CTFontRef font = CFAttributedStringGetAttribute(attributed, 0, kCTFontAttributeName, NULL);
assert(font);
// compute vertical position from font metrics
CGFloat belowBaseline = CTFontGetLeading(font) + CTFontGetDescent(font) + vertMargin;
CGFloat lineHeight = belowBaseline + CTFontGetAscent(font) + vertMargin;
// Make a CTLine to render from the attributed string
CTLineRef line = CTLineCreateWithAttributedString(attributed);
CFRelease(attributed);
// Generate a bitmap context at the correct resolution
UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
CGContextRef context = UIGraphicsGetCurrentContext();
// flip y
CGContextTranslateCTM(context, 0.0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGFloat x = horizMargin;
CGFloat y = belowBaseline / lineHeight * size.height;
CGContextSetTextPosition(context, x, y);
CTLineDraw(line, context);
CFRelease(line);
// Get the generated bitmap and use it for the layer's contents.
self.contents = (id)UIGraphicsGetImageFromCurrentImageContext().CGImage;
UIGraphicsEndImageContext();
}
- (CFAttributedStringRef)attributedString
{
CGFloat fontSize = _fontSize * [UIScreen mainScreen].scale;
CTFontRef font;
CFAttributedStringRef attributed;
_ignoringForegroundColor = _ignoringFontName = _ignoringFontSize = NO;
/*
* _string can be an attributed string or a plain string. in the end, we need an attributed string.
*/
if ([_string isKindOfClass:NSAttributedString.class]) {
/*
* It's an attributed string. Make a mutable copy.
*/
CFMutableAttributedStringRef mutableAttributed = CFAttributedStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFAttributedStringRef)_string);
attributed = mutableAttributed;
CFRange wholeString;
wholeString.location = 0;
wholeString.length = CFAttributedStringGetLength(attributed);
font = CFAttributedStringGetAttribute(attributed, 0, kCTFontAttributeName, NULL);
/*
* Massage the font attribute for a number of reasons:
* 1. No font was specified for the input (like a plain string)
*/
BOOL createdNewFont = NO;
if (!font) {
createdNewFont = YES;
font = CTFontCreateWithName((CFStringRef)_fontName, fontSize, NULL);
CFAttributedStringSetAttribute(mutableAttributed, wholeString, kCTFontAttributeName, font);
CFRelease(font);
}
assert(font);
CGFloat pointSize = CTFontGetSize(font);
// NSLog(@"point size for attrib. string: %f", pointSize);
// 2. It's at the top and has to zoom.
if (_adjustsFontSizeForAttributed && pointSize != fontSize) {
/*
* Need to adjust to the specified fontSize
*/
CTFontRef newFont = CTFontCreateCopyWithAttributes(font, fontSize, NULL, NULL);
CFAttributedStringSetAttribute(mutableAttributed, wholeString, kCTFontAttributeName, newFont);
CFRelease(newFont);
// NSLog(@"point size for new font: %f", fontSize);
_ignoringFontName = !createdNewFont;
_ignoringFontSize = NO;
}
// 3. This is a high-res image, so we render at double the size.
else if (!_adjustsFontSizeForAttributed && [UIScreen mainScreen].scale > 1.0) {
/*
* Need to increase the font size for this hi-res image
*/
fontSize = [UIScreen mainScreen].scale * pointSize;
CTFontRef newFont = CTFontCreateCopyWithAttributes(font, fontSize, NULL, NULL);
CFAttributedStringSetAttribute(mutableAttributed, wholeString, kCTFontAttributeName, newFont);
CFRelease(newFont);
// NSLog(@"point size for new font: %f", fontSize);
_ignoringFontName = !createdNewFont;
_ignoringFontSize = !createdNewFont;
}
else {
/*
* No change. Update the fontName attribute.
*/
font = CFAttributedStringGetAttribute(attributed, 0, kCTFontAttributeName, NULL);
_fontName = CFBridgingRelease(CTFontCopyPostScriptName(font));
_ignoringFontName = !createdNewFont;
_ignoringFontSize = !createdNewFont;
}
/*
* As with views like UILabel, reset the foregroundColor and fontName properties to those attributes of the
* string at location 0.
*/
CGColorRef fg = (CGColorRef)CFAttributedStringGetAttribute(attributed, 0, kCTForegroundColorAttributeName, NULL);
if (fg) {
_ignoringForegroundColor = YES;
self.foregroundColor = fg;
}
else {
/*
* kCTForegroundColorAttributeName == "CTForegroundColor"
* NSForegroundColorAttributeName == "NSColor"
*
* Apparently in iOS 7, these attributes were bridged/mapped/whatever. That is, the view controller could construct an
* NSAttributedString using NSForegroundColorAttributeName, and in here, a check for kCTForegroundColorAttributeName
* would produce the same value. But that's no longer the case in iOS 8. So we accept both here.
*/
fg = (CGColorRef)CFAttributedStringGetAttribute(attributed, 0, (__bridge CFStringRef)NSForegroundColorAttributeName, NULL);
if (fg) {
_ignoringForegroundColor = YES;
self.foregroundColor = fg;
}
else {
// no foreground color specified, so give it one (like a plain string)
CFAttributedStringSetAttribute(mutableAttributed, wholeString, kCTForegroundColorAttributeName, _foregroundColor);
}
}
_fontSize = fontSize / [UIScreen mainScreen].scale;
}
else {
/*
* Plain string. Get the necessary font.
*/
font = CTFontCreateWithName((CFStringRef)_fontName, fontSize, NULL);
assert(font);
/*
CFStringRef fname = CTFontCopyPostScriptName(font);
NSLog(@"Using font %@", (__bridge NSString*)fname);
CFRelease(fname);
// */
CFStringRef keys[] = { kCTFontAttributeName, kCTForegroundColorAttributeName };
CFTypeRef values[] = { font, _foregroundColor };
CFDictionaryRef attributes =
CFDictionaryCreate(kCFAllocatorDefault, (const void**)&keys,
(const void**)&values, sizeof(keys) / sizeof(keys[0]),
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFRelease(font);
// create an attributed string with a foreground color and a font
attributed = CFAttributedStringCreate(kCFAllocatorDefault, (CFStringRef)_string, attributes);
CFRelease(attributes);
}
return attributed;
}
@end
#pragma mark - IOSKnobControl implementation
@interface IOSKnobControl()
/*
* Returns the nearest allowed position
*/
@property (readonly) float nearestPosition;
@property (readonly) BOOL currentFillColorIsOpaque;
@property (readonly) UIBezierPath* rotaryDialPath;
@property (readonly) CGRect roundedBounds;
@end
@implementation IOSKnobControl {
float touchStart, positionStart, currentTouch;
UIGestureRecognizer* gestureRecognizer;
CALayer* imageLayer, *backgroundLayer, *foregroundLayer, *middleLayer, *shadowLayer;
CAShapeLayer* shapeLayer, *pipLayer, *stopLayer;
NSMutableArray* markings, *dialMarkings;
UIImage* images[4];
UIColor* fillColor[4];
UIColor* titleColor[4];
BOOL rotating;
int lastNumberDialed, _numberDialed;
NSInteger lastPositionIndex;
}
@dynamic positionIndex, nearestPosition;
#pragma mark - Object Lifecycle
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setDefaults];
[self setupGestureRecognizer];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame image:(UIImage *)image
{
self = [super initWithFrame:frame];
if (self) {
[self setImage:image forState:UIControlStateNormal];
[self setDefaults];
[self setupGestureRecognizer];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame imageNamed:(NSString *)imageSetName
{
self = [super initWithFrame:frame];
if (self) {
UIImage* image = [UIImage imageNamed:imageSetName];
[self setImage:image forState:UIControlStateNormal];
[self setDefaults];
[self setupGestureRecognizer];
}
return self;
}
- (void)setDefaults
{
_mode = IKCModeLinearReturn;
_clockwise = NO;
_position = 0.0;
_circular = YES;
_min = -M_PI + IKC_EPSILON;
_max = M_PI - IKC_EPSILON;
_positions = 2;
_timeScale = 1.0;
_gesture = IKCGestureOneFingerRotation;
_normalized = YES;
_fontName = @"Helvetica";
_shadowRadius = 3.0;
_shadowColor = [UIColor blackColor];
_shadowOpacity = 0.0;
_shadowOffset = CGSizeMake(0.0, 3.0);
_knobRadius = 0.5 * self.bounds.size.width;
_zoomTopTitle = YES;
_zoomPointSize = 0.0;
_drawsAsynchronously = NO;
_fingerHoleRadius = IKC_DEFAULT_FINGER_HOLE_RADIUS;
_masksImage = NO;
_gestureSensitivity = 1.0;
// Default margin is the same as the space between adjacent holes
_fingerHoleMargin = (_knobRadius - 4.86*_fingerHoleRadius)/2.93;
rotating = NO;
lastNumberDialed = _numberDialed = -1;
lastPositionIndex = 0;
self.opaque = NO;
self.backgroundColor = [UIColor clearColor];
self.clipsToBounds = YES;
}
#pragma mark - Public Methods, Properties and Overrides
- (UIImage *)imageForState:(UIControlState)state
{
int index = [self indexForState:state];
/*
* Like UIButton, use the image for UIControlStateNormal if none present.
*/
// Mmmm. Double square brackets in the last expression of the ternary conditional: outer for the array subscript, inner for a method call.
return index >= 0 && images[index] ? images[index] : images[[self indexForState:UIControlStateNormal]];
}
- (void)setImage:(UIImage *)image forState:(UIControlState)state
{
int index = [self indexForState:state];
/*
* Don't accept mixed states here. Cannot pass, e.g., UIControlStateHighlighted & UIControlStateDisabled.
* Those values are ignored here.
*/
if (state == UIControlStateNormal || state == UIControlStateHighlighted || state == UIControlStateDisabled || state == UIControlStateSelected) {
images[index] = image;
}
/*
* The method parameter state must be one of the four enumerated values listed above.
* But self.state could be a mixed state. Conceivably, the control could be
* both disabled and highlighted. In that case, since disabled is numerically
* greater than highlighted, we return the index/image for UIControlStateDisabled.
* (See indexForState: below.) That is to say, the following expression is always true:
* [self indexForState:UIControlStateDisabled] == [self indexForState:UIControlStateHighlighted|UIControlStateDisabled]
* If we just now changed the image currently in use (the image for the current state), update it now.
*/
if (index == [self indexForState:self.state]) {
[self setNeedsLayout];
}
}
- (UIColor *)fillColorForState:(UIControlState)state
{
int index = [self indexForState:state];
UIColor* color = index >= 0 && fillColor[index] ? fillColor[index] : fillColor[[self indexForState:UIControlStateNormal]];
if (!color) {
CGFloat red, green, blue, alpha;
[self.getTintColor getRed:&red green:&green blue:&blue alpha:&alpha];
CGFloat hue, saturation, brightness;
[self.getTintColor getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
if ((red == green && green == blue) || brightness < 0.02) {
/*
* This is for any shade of gray from black to white. Unfortunately, black is not really black.
* It comes out as a red hue. Hence the brightness test above.
*/
CGFloat value = ((NSNumber*)@[@(0.6), @(0.8), @(0.9), @(0.8)][index]).floatValue;
color = [UIColor colorWithRed:value green:value blue:value alpha:alpha];
}
else {
saturation = ((NSNumber*)@[@(1.0), @(0.7), @(0.2), @(0.7)][index]).floatValue;
brightness = ((NSNumber*)@[@(0.9), @(1.0), @(0.9), @(1.0)][index]).floatValue;
color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:alpha];
}
}
return color;
}
- (void)setFillColor:(UIColor *)color forState:(UIControlState)state
{
int index = [self indexForState:state];
if (state == UIControlStateNormal || state == UIControlStateHighlighted || state == UIControlStateDisabled || state == UIControlStateSelected) {
fillColor[index] = color;
}
if (index == [self indexForState:self.state]) {
[self setNeedsLayout];
}
}
- (UIColor *)titleColorForState:(UIControlState)state
{
int index = [self indexForState:state];
UIColor* color = index >= 0 && titleColor[index] ? titleColor[index] : titleColor[[self indexForState:UIControlStateNormal]];
if (!color) {
CGFloat red, green, blue, alpha;
[self.getTintColor getRed:&red green:&green blue:&blue alpha:&alpha];
CGFloat hue, saturation, brightness;
[self.getTintColor getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
if ((red == green && green == blue) || brightness < 0.02) {
/*
* This is for any shade of gray from black to white. Unfortunately, black is not really black.
* It comes out as a red hue. Hence the brightness test above.
*/
CGFloat value = ((NSNumber*)@[@(0.25), @(0.25), @(0.4), @(0.25)][index]).floatValue;
color = [UIColor colorWithRed:value green:value blue:value alpha:alpha];
}
else {
saturation = ((NSNumber*)@[@(1.0), @(1.0), @(0.2), @(1.0)][index]).floatValue;
brightness = 0.5; // ((NSNumber*)@[@(0.5), @(0.5), @(0.5), @(0.5)][index]).floatValue;
color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:alpha];
}
}
return color;
}
- (void)setTitleColor:(UIColor *)color forState:(UIControlState)state
{
int index = [self indexForState:state];
if (state == UIControlStateNormal || state == UIControlStateHighlighted || state == UIControlStateDisabled || state == UIControlStateSelected) {
titleColor[index] = color;
}
if (index == [self indexForState:self.state]) {
[self setNeedsLayout];
}
}
- (void)setFrame:(CGRect)frame
{
if (_mode == IKCModeRotaryDial)
{
frame = adjustFrame(frame, _fingerHoleRadius);
}
[super setFrame:frame];
[self setNeedsLayout];
}
- (void)setBackgroundImage:(UIImage *)backgroundImage
{
_backgroundImage = backgroundImage;
[self setNeedsLayout];
}
- (void)setForegroundImage:(UIImage *)foregroundImage
{
_foregroundImage = foregroundImage;
[self setNeedsLayout];
}
- (void)setEnabled:(BOOL)enabled
{
[super setEnabled:enabled];
gestureRecognizer.enabled = enabled;
[self updateControlState];
}
- (void)setHighlighted:(BOOL)highlighted
{
[super setHighlighted:highlighted];
[self updateControlState];
}
- (void)setSelected:(BOOL)selected
{
[super setSelected:selected];
[self updateControlState];
}
- (void)setPositions:(NSUInteger)positions
{
if (_positions == positions) return;
_positions = positions;
[imageLayer removeFromSuperlayer];
shapeLayer = nil;
imageLayer = [self createShapeLayer];
[self addMarkings]; // gets rid of any old ones
[self.layer addSublayer:imageLayer];
}
- (void)setTitles:(NSArray *)titles
{
/*
* DEBT: Actually, titles can be set on a control using images. It's the absence of the
* image that triggers use of the titles. The property can be populated in advance of
* removing images.
*/
_titles = titles;
[imageLayer removeFromSuperlayer];
shapeLayer = nil;
imageLayer = [self createShapeLayer];
[self.layer addSublayer:imageLayer];
}
- (void)setMode:(IKCMode)mode
{
_mode = mode;
[self setNeedsLayout];
if (_mode == IKCModeRotaryDial)
{
if (_gesture == IKCGestureVerticalPan || _gesture == IKCGestureTwoFingerRotation)
{
_gesture = IKCGestureOneFingerRotation;
}
_clockwise = NO; // dial clockwise, but all calcs assume ccw
_circular = NO;
_max = IKC_EPSILON;
_min = -11.0*M_PI/6.0;
self.frame = adjustFrame(self.frame, _fingerHoleRadius);
lastNumberDialed = 0;
}
}
- (void)setCircular:(BOOL)circular
{
if (_mode == IKCModeRotaryDial) return;
_circular = circular;
if (!_circular) {
self.position = MIN(MAX(_position, _min), _max);
}
else if (_normalized) {
while (_position > M_PI) _position -= 2.0 * M_PI;
while (_position <= -M_PI) _position += 2.0 * M_PI;
}
[self setNeedsLayout];
}
- (void)setClockwise:(BOOL)clockwise
{
if (_mode == IKCModeRotaryDial) return;
_clockwise = clockwise;
[imageLayer removeFromSuperlayer];
shapeLayer = nil;
imageLayer = [self createShapeLayer];
[self.layer addSublayer:imageLayer];
[self setNeedsLayout];
}
- (void)setPosition:(float)position
{
[self setPosition:position animated:NO];
}
- (void)setPosition:(float)position animated:(BOOL)animated
{
if (_circular == NO) {
position = MAX(position, _min);
position = MIN(position, _max);
}
else if (_normalized) {
while (position > M_PI) position -= 2.0*M_PI;
while (position <= -M_PI) position += 2.0*M_PI;
if (position == -M_PI) position = M_PI;
}
float delta = fabs(position - _position);
// ignore _timeScale. rotate through 2*M_PI in 1 s.
[self returnToPosition:position duration:animated ? delta*0.5/M_PI : 0.0];
}
- (void)setPositionIndex:(NSInteger)positionIndex
{
if (self.mode == IKCModeContinuous || self.mode == IKCModeRotaryDial) return;
float position = self.circular ? (2.0*M_PI/_positions)*positionIndex : ((self.max - self.min)/_positions)*(positionIndex+0.5) + self.min;
[self setPosition:position animated:NO];
}
- (NSInteger)positionIndex
{
if (self.mode == IKCModeContinuous) return -1;
if (self.mode == IKCModeRotaryDial) return lastNumberDialed;
return [self positionIndexForPosition:_position];
}
/*
* This override is to fix #3.
*/
- (BOOL)isHighlighted
{
return rotating || [super isHighlighted];
}
- (void)setMin:(float)min
{
// this property is effectively readonly in this mode
if (_mode == IKCModeRotaryDial) return;
_min = min;
if (_max - _min >= 2.0*M_PI) _max = _min + 2.0*M_PI;
if (_max < _min) _max = _min;
if (_position < _min) self.position = _min;
if (_mode == IKCModeContinuous || self.currentImage) return;
// if we are rendering a discrete knob with titles, re-render the titles now that min/max has changed
[imageLayer removeFromSuperlayer];
shapeLayer = nil;
imageLayer = [self createShapeLayer];
[self.layer addSublayer:imageLayer];
}
- (void)setMax:(float)max
{
// this property is effectively readonly in this mode
if (_mode == IKCModeRotaryDial) return;
_max = max;
if (_max - _min >= 2.0*M_PI) _min = _max - 2.0*M_PI;
if (_max < _min) _min = _max;
if (_position > _max) self.position = _max;
if (_mode == IKCModeContinuous || self.currentImage) return;
// if we are rendering a discrete knob with titles, re-render the titles now that min/max has changed
[imageLayer removeFromSuperlayer];
shapeLayer = nil;
imageLayer = [self createShapeLayer];
[self.layer addSublayer:imageLayer];
}
- (void)setGesture:(IKCGesture)gesture
{
if (_mode == IKCModeRotaryDial && (gesture == IKCGestureTwoFingerRotation || gesture == IKCGestureVerticalPan))
{
#ifdef DEBUG
NSLog(@"IKCModeRotaryDial only allows IKCGestureOneFingerRotation and IKCGestureTap");
#endif // DEBUG
return;
}
_gesture = gesture;
[self setupGestureRecognizer];
}
- (void)setNormalized:(BOOL)normalized
{
_normalized = normalized;
if (!_circular) {
self.position = MIN(MAX(_position, _min), _max);
}
else if (_normalized) {
while (_position > M_PI) _position -= 2.0 * M_PI;
while (_position <= -M_PI) _position += 2.0 * M_PI;
}
[self setNeedsLayout];
}
- (void)setFontName:(NSString *)fontName
{
UIFontDescriptor* fontDescriptor = [UIFontDescriptor fontDescriptorWithName:fontName size:0.0];
if ([fontDescriptor matchingFontDescriptorsWithMandatoryKeys:nil].count == 0) {
/*
* On iOS 6, the matchingBlah: call returns 0 for valid fonts. So we do this check too
* before giving up.
*/
UIFontDescriptor* fontDescriptor = [UIFontDescriptor fontDescriptorWithName:fontName size:17.0];
if (![UIFont fontWithDescriptor:fontDescriptor size:0.0] && ![UIFont fontWithName:fontName size:17.0]) {
NSLog(@"Failed to find font name \"%@\".", fontName);
return;
}
}
_fontName = fontName;
[self setNeedsLayout];
}
- (void)setZoomTopTitle:(BOOL)zoomTopTitle
{
_zoomTopTitle = zoomTopTitle;
[self setNeedsLayout];
}
- (void)setDrawsAsynchronously:(BOOL)drawsAsynchronously
{
_drawsAsynchronously = drawsAsynchronously;
[self setNeedsLayout];
}
- (void)setShadowColor:(UIColor *)shadowColor
{
_shadowColor = shadowColor;
[self setNeedsLayout];
}
- (void)setShadowOffset:(CGSize)shadowOffset
{
_shadowOffset = shadowOffset;
[self setNeedsLayout];
}
- (void)setShadowOpacity:(CGFloat)shadowOpacity
{
_shadowOpacity = shadowOpacity;
[self setNeedsLayout];
}
- (void)setShadowRadius:(CGFloat)shadowRadius
{
_shadowRadius = shadowRadius;
[self setNeedsLayout];
}
- (void)setMiddleLayerShadowPath:(UIBezierPath *)middleLayerShadowPath
{
_middleLayerShadowPath = middleLayerShadowPath;
[self setNeedsLayout];
}
- (void)setForegroundLayerShadowPath:(UIBezierPath *)foregroundLayerShadowPath
{
_foregroundLayerShadowPath = foregroundLayerShadowPath;
[self setNeedsLayout];
}
- (void)setKnobRadius:(CGFloat)knobRadius
{
_knobRadius = knobRadius;
[self setNeedsLayout];
}
- (void)setFingerHoleRadius:(CGFloat)fingerHoleRadius
{
_fingerHoleRadius = fingerHoleRadius;
self.frame = adjustFrame(self.frame, _fingerHoleRadius);
[self setNeedsLayout];
}
- (void)setFingerHoleMargin:(CGFloat)fingerHoleMargin
{
_fingerHoleMargin = fingerHoleMargin;
[self setNeedsLayout];
}
- (void)setMasksImage:(BOOL)maskImage
{
_masksImage = maskImage;
[self setNeedsLayout];
}
- (void)tintColorDidChange
{
[self setNeedsLayout];
}
- (UIImage*)currentImage
{
return [self imageForState:self.state];
}
- (UIColor*)currentFillColor
{
return [self fillColorForState:self.state];
}
- (UIColor*)currentTitleColor
{
return [self titleColorForState:self.state];
}
- (void)dialNumber:(int)number
{