-
Notifications
You must be signed in to change notification settings - Fork 367
/
CosmosDistrib.swift
1603 lines (1130 loc) · 44.5 KB
/
CosmosDistrib.swift
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
//
// Star rating control written in Swift for iOS and tvOS.
//
// https://github.com/evgenyneu/Cosmos
//
// This file was automatically generated by combining multiple Swift source files.
//
// ----------------------------
//
// StarFillMode.swift
//
// ----------------------------
import Foundation
/**
Defines how the star is filled when the rating is not an integer number. For example, if rating is 4.6 and the fill more is Half, the star will appear to be half filled.
*/
public enum StarFillMode: Int {
/// Show only fully filled stars. For example, fourth star will be empty for 3.2.
case full = 0
/// Show fully filled and half-filled stars. For example, fourth star will be half filled for 3.6.
case half = 1
/// Fill star according to decimal rating. For example, fourth star will be 20% filled for 3.2.
case precise = 2
}
// ----------------------------
//
// StarLayer.swift
//
// ----------------------------
import UIKit
/**
Creates a layer with a single star in it.
*/
struct StarLayer {
/**
Creates a square layer with given size and draws the star shape in it.
- parameter starPoints: Array of points for drawing a closed shape. The size of enclosing rectangle is 100 by 100.
- parameter size: The width and height of the layer. The star shape is scaled to fill the size of the layer.
- parameter lineWidth: The width of the star stroke.
- parameter fillColor: Star shape fill color. Fill color is invisible if it is a clear color.
- parameter strokeColor: Star shape stroke color. Stroke is invisible if it is a clear color.
- returns: New layer containing the star shape.
*/
static func create(_ starPoints: [CGPoint], size: Double,
lineWidth: Double, fillColor: UIColor, strokeColor: UIColor) -> CALayer {
let containerLayer = createContainerLayer(size)
let path = createStarPath(starPoints, size: size, lineWidth: lineWidth)
let shapeLayer = createShapeLayer(path.cgPath, lineWidth: lineWidth,
fillColor: fillColor, strokeColor: strokeColor, size: size)
containerLayer.addSublayer(shapeLayer)
return containerLayer
}
/**
Creates the star layer from an image
- parameter image: a star image to be shown.
- parameter size: The width and height of the layer. The image is scaled to fit the layer.
*/
static func create(image: UIImage, size: Double) -> CALayer {
let containerLayer = createContainerLayer(size)
let imageLayer = createContainerLayer(size)
containerLayer.addSublayer(imageLayer)
imageLayer.contents = image.cgImage
imageLayer.contentsGravity = CALayerContentsGravity.resizeAspect
return containerLayer
}
/**
Creates the star shape layer.
- parameter path: The star shape path.
- parameter lineWidth: The width of the star stroke.
- parameter fillColor: Star shape fill color. Fill color is invisible if it is a clear color.
- parameter strokeColor: Star shape stroke color. Stroke is invisible if it is a clear color.
- returns: New shape layer.
*/
static func createShapeLayer(_ path: CGPath, lineWidth: Double, fillColor: UIColor,
strokeColor: UIColor, size: Double) -> CALayer {
let layer = CAShapeLayer()
layer.anchorPoint = CGPoint()
layer.contentsScale = UIScreen.main.scale
layer.strokeColor = strokeColor.cgColor
layer.fillColor = fillColor.cgColor
layer.lineWidth = CGFloat(lineWidth)
layer.bounds.size = CGSize(width: size, height: size)
layer.masksToBounds = true
layer.path = path
layer.isOpaque = true
return layer
}
/**
Creates a layer that will contain the shape layer.
- returns: New container layer.
*/
static func createContainerLayer(_ size: Double) -> CALayer {
let layer = CALayer()
layer.contentsScale = UIScreen.main.scale
layer.anchorPoint = CGPoint()
layer.masksToBounds = true
layer.bounds.size = CGSize(width: size, height: size)
layer.isOpaque = true
return layer
}
/**
Creates a path for the given star points and size. The star points specify a shape of size 100 by 100. The star shape will be scaled if the size parameter is not 100. For exampe, if size parameter is 200 the shape will be scaled by 2.
- parameter starPoints: Array of points for drawing a closed shape. The size of enclosing rectangle is 100 by 100.
- parameter size: Specifies the size of the shape to return.
- returns: New shape path.
*/
static func createStarPath(_ starPoints: [CGPoint], size: Double,
lineWidth: Double) -> UIBezierPath {
let lineWidthLocal = lineWidth + ceil(lineWidth * 0.3)
let sizeWithoutLineWidth = size - lineWidthLocal * 2
let points = scaleStar(starPoints, factor: sizeWithoutLineWidth / 100,
lineWidth: lineWidthLocal)
let path = UIBezierPath()
path.move(to: points[0])
let remainingPoints = Array(points[1..<points.count])
for point in remainingPoints {
path.addLine(to: point)
}
path.close()
return path
}
/**
Scale the star points by the given factor.
- parameter starPoints: Array of points for drawing a closed shape. The size of enclosing rectangle is 100 by 100.
- parameter factor: The factor by which the star points are scaled. For example, if it is 0.5 the output points will define the shape twice as small as the original.
- returns: The scaled shape.
*/
static func scaleStar(_ starPoints: [CGPoint], factor: Double, lineWidth: Double) -> [CGPoint] {
return starPoints.map { point in
return CGPoint(
x: point.x * CGFloat(factor) + CGFloat(lineWidth),
y: point.y * CGFloat(factor) + CGFloat(lineWidth)
)
}
}
}
// ----------------------------
//
// CosmosAccessibility.swift
//
// ----------------------------
import UIKit
/**
Functions for making cosmos view accessible.
*/
struct CosmosAccessibility {
/**
Makes the view accesible by settings its label and using rating as value.
*/
static func update(_ view: UIView, rating: Double, text: String?, settings: CosmosSettings) {
view.isAccessibilityElement = true
view.accessibilityTraits = settings.updateOnTouch ?
UIAccessibilityTraits.adjustable :UIAccessibilityTraits.none
var accessibilityLabel = CosmosLocalizedRating.ratingTranslation
if let text = text, text != "" {
accessibilityLabel += " \(text)"
}
view.accessibilityLabel = accessibilityLabel
view.accessibilityValue = accessibilityValue(view, rating: rating, settings: settings)
}
/**
Returns the rating that is used as accessibility value.
The accessibility value depends on the star fill mode.
For example, if rating is 4.6 and fill mode is .half the value will be 4.5. And if the fill mode
if .full the value will be 5.
*/
static func accessibilityValue(_ view: UIView, rating: Double, settings: CosmosSettings) -> String {
let accessibilityRating = CosmosRating.displayedRatingFromPreciseRating(rating,
fillMode: settings.fillMode, totalStars: settings.totalStars)
// Omit decimals if the value is an integer
let isInteger = (accessibilityRating * 10).truncatingRemainder(dividingBy: 10) == 0
if isInteger {
return "\(Int(accessibilityRating))"
} else {
// Only show a single decimal place
let roundedToFirstDecimalPlace = Double( round(10 * accessibilityRating) / 10 )
return "\(roundedToFirstDecimalPlace)"
}
}
/**
Returns the amount of increment for the rating. When .half and .precise fill modes are used the
rating is incremented by 0.5.
*/
static func accessibilityIncrement(_ rating: Double, settings: CosmosSettings) -> Double {
var increment: Double = 0
switch settings.fillMode {
case .full:
increment = ceil(rating) - rating
if increment == 0 { increment = 1 }
case .half, .precise:
increment = (ceil(rating * 2) - rating * 2) / 2
if increment == 0 { increment = 0.5 }
}
if rating >= Double(settings.totalStars) { increment = 0 }
let roundedToFirstDecimalPlace = Double( round(10 * increment) / 10 )
return roundedToFirstDecimalPlace
}
static func accessibilityDecrement(_ rating: Double, settings: CosmosSettings) -> Double {
var increment: Double = 0
switch settings.fillMode {
case .full:
increment = rating - floor(rating)
if increment == 0 { increment = 1 }
case .half, .precise:
increment = (rating * 2 - floor(rating * 2)) / 2
if increment == 0 { increment = 0.5 }
}
if rating <= settings.minTouchRating { increment = 0 }
let roundedToFirstDecimalPlace = Double( round(10 * increment) / 10 )
return roundedToFirstDecimalPlace
}
}
// ----------------------------
//
// CosmosText.swift
//
// ----------------------------
import UIKit
/**
Positions the text layer to the right of the stars.
*/
class CosmosText {
/**
Positions the text layer to the right from the stars. Text is aligned to the center of the star superview vertically.
- parameter layer: The text layer to be positioned.
- parameter starsSize: The size of the star superview.
- parameter textMargin: The distance between the stars and the text.
*/
class func position(_ layer: CALayer, starsSize: CGSize, textMargin: Double) {
layer.position.x = starsSize.width + CGFloat(textMargin)
let yOffset = (starsSize.height - layer.bounds.height) / 2
layer.position.y = yOffset
}
}
// ----------------------------
//
// CosmosDefaultSettings.swift
//
// ----------------------------
import UIKit
/**
Defaults setting values.
*/
struct CosmosDefaultSettings {
init() {}
static let defaultColor = UIColor(red: 1, green: 149/255, blue: 0, alpha: 1)
// MARK: - Star settings
// -----------------------------
/// Border color of an empty star.
static let emptyBorderColor = defaultColor
/// Width of the border for the empty star.
static let emptyBorderWidth: Double = 1 / Double(UIScreen.main.scale)
/// Border color of a filled star.
static let filledBorderColor = defaultColor
/// Width of the border for a filled star.
static let filledBorderWidth: Double = 1 / Double(UIScreen.main.scale)
/// Background color of an empty star.
static let emptyColor = UIColor.clear
/// Background color of a filled star.
static let filledColor = defaultColor
/**
Defines how the star is filled when the rating value is not an integer value. It can either show full stars, half stars or stars partially filled according to the rating value.
*/
static let fillMode = StarFillMode.full
/// Rating value that is shown in the storyboard by default.
static let rating: Double = 2.718281828
/// Distance between stars.
static let starMargin: Double = 5
/**
Array of points for drawing the star with size of 100 by 100 pixels. Supply your points if you need to draw a different shape.
*/
static let starPoints: [CGPoint] = [
CGPoint(x: 49.5, y: 0.0),
CGPoint(x: 60.5, y: 35.0),
CGPoint(x: 99.0, y: 35.0),
CGPoint(x: 67.5, y: 58.0),
CGPoint(x: 78.5, y: 92.0),
CGPoint(x: 49.5, y: 71.0),
CGPoint(x: 20.5, y: 92.0),
CGPoint(x: 31.5, y: 58.0),
CGPoint(x: 0.0, y: 35.0),
CGPoint(x: 38.5, y: 35.0)
]
/// Size of a single star.
static var starSize: Double = 20
/// The total number of stars to be shown.
static let totalStars = 5
// MARK: - Text settings
// -----------------------------
/// Color of the text.
static let textColor = UIColor(red: 127/255, green: 127/255, blue: 127/255, alpha: 1)
/// Font for the text.
static let textFont = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.footnote)
/// Distance between the text and the stars.
static let textMargin: Double = 5
/// Calculates the size of the default text font. It is used for making the text size configurable from the storyboard.
static var textSize: Double {
get {
return Double(textFont.pointSize)
}
}
// MARK: - Touch settings
// -----------------------------
/// The lowest rating that user can set by touching the stars.
static let minTouchRating: Double = 1
/// Set to `false` if you don't want to pass touches to superview (can be useful in a table view).
static let passTouchesToSuperview = true
/// When `true` the star fill level is updated when user touches the cosmos view. When `false` the Cosmos view only shows the rating and does not act as the input control.
static let updateOnTouch = true
}
// ----------------------------
//
// CosmosSize.swift
//
// ----------------------------
import UIKit
/**
Helper class for calculating size for the cosmos view.
*/
class CosmosSize {
/**
Calculates the size of the cosmos view. It goes through all the star and text layers and makes size the view size is large enough to show all of them.
*/
class func calculateSizeToFitLayers(_ layers: [CALayer]) -> CGSize {
var size = CGSize()
for layer in layers {
if layer.frame.maxX > size.width {
size.width = layer.frame.maxX
}
if layer.frame.maxY > size.height {
size.height = layer.frame.maxY
}
}
return size
}
}
// ----------------------------
//
// CosmosLayers.swift
//
// ----------------------------
import UIKit
/**
Colection of helper functions for creating star layers.
*/
class CosmosLayers {
/**
Creates the layers for the stars.
- parameter rating: The decimal number representing the rating. Usually a number between 1 and 5
- parameter settings: Star view settings.
- returns: Array of star layers.
*/
class func createStarLayers(_ rating: Double, settings: CosmosSettings, isRightToLeft: Bool) -> [CALayer] {
var ratingRemander = CosmosRating.numberOfFilledStars(rating,
totalNumberOfStars: settings.totalStars)
var starLayers = [CALayer]()
for _ in (0..<settings.totalStars) {
let fillLevel = CosmosRating.starFillLevel(ratingRemainder: ratingRemander,
fillMode: settings.fillMode)
let starLayer = createCompositeStarLayer(fillLevel, settings: settings, isRightToLeft: isRightToLeft)
starLayers.append(starLayer)
ratingRemander -= 1
}
if isRightToLeft { starLayers.reverse() }
positionStarLayers(starLayers, starMargin: settings.starMargin)
return starLayers
}
/**
Creates an layer that shows a star that can look empty, fully filled or partially filled.
Partially filled layer contains two sublayers.
- parameter starFillLevel: Decimal number between 0 and 1 describing the star fill level.
- parameter settings: Star view settings.
- returns: Layer that shows the star. The layer is displayed in the cosmos view.
*/
class func createCompositeStarLayer(_ starFillLevel: Double,
settings: CosmosSettings, isRightToLeft: Bool) -> CALayer {
if starFillLevel >= 1 {
return createStarLayer(true, settings: settings)
}
if starFillLevel == 0 {
return createStarLayer(false, settings: settings)
}
return createPartialStar(starFillLevel, settings: settings, isRightToLeft: isRightToLeft)
}
/**
Creates a partially filled star layer with two sub-layers:
1. The layer for the filled star on top. The fill level parameter determines the width of this layer.
2. The layer for the empty star below.
- parameter starFillLevel: Decimal number between 0 and 1 describing the star fill level.
- parameter settings: Star view settings.
- returns: Layer that contains the partially filled star.
*/
class func createPartialStar(_ starFillLevel: Double, settings: CosmosSettings, isRightToLeft: Bool) -> CALayer {
let filledStar = createStarLayer(true, settings: settings)
let emptyStar = createStarLayer(false, settings: settings)
let parentLayer = CALayer()
parentLayer.contentsScale = UIScreen.main.scale
parentLayer.bounds = CGRect(origin: CGPoint(), size: filledStar.bounds.size)
parentLayer.anchorPoint = CGPoint()
parentLayer.addSublayer(emptyStar)
parentLayer.addSublayer(filledStar)
if isRightToLeft {
// Flip the star horizontally for a right-to-left language
let rotation = CATransform3DMakeRotation(CGFloat(Double.pi), 0, 1, 0)
filledStar.transform = CATransform3DTranslate(rotation, -filledStar.bounds.size.width, 0, 0)
}
// Make filled layer width smaller according to the fill level
filledStar.bounds.size.width *= CGFloat(starFillLevel)
return parentLayer
}
private class func createStarLayer(_ isFilled: Bool, settings: CosmosSettings) -> CALayer {
if let image = isFilled ? settings.filledImage : settings.emptyImage {
// Create a layer that shows a star from an image
return StarLayer.create(image: image, size: settings.starSize)
}
// Create a layer that draws a star from an array of points
let fillColor = isFilled ? settings.filledColor : settings.emptyColor
let strokeColor = isFilled ? settings.filledBorderColor : settings.emptyBorderColor
return StarLayer.create(settings.starPoints,
size: settings.starSize,
lineWidth: isFilled ? settings.filledBorderWidth : settings.emptyBorderWidth,
fillColor: fillColor,
strokeColor: strokeColor)
}
/**
Positions the star layers one after another with a margin in between.
- parameter layers: The star layers array.
- parameter starMargin: Margin between stars.
*/
class func positionStarLayers(_ layers: [CALayer], starMargin: Double) {
var positionX:CGFloat = 0
for layer in layers {
layer.position.x = positionX
positionX += layer.bounds.width + CGFloat(starMargin)
}
}
}
// ----------------------------
//
// CosmosLocalizedRating.swift
//
// ----------------------------
import Foundation
/**
Returns the word "Rating" in user's language. It is used for voice-over in accessibility mode.
*/
struct CosmosLocalizedRating {
static var defaultText = "Rating"
static var localizedRatings = [
"ar": "تصنيف",
"bg": "Рейтинг",
"cy": "Sgôr",
"da": "Rating",
"de": "Bewertung",
"el": "Βαθμολογία",
"en": defaultText,
"es": "Valorar",
"et": "Reiting",
"fi": "Luokitus",
"fr": "De note",
"he": "דירוג",
"hi": "रेटिंग",
"hr": "Ocjena",
"hu": "Értékelés",
"id": "Peringkat",
"it": "Voto",
"ko": "등급",
"lt": "Reitingas",
"lv": "Vērtējums",
"nl": "Rating",
"no": "Vurdering",
"pl": "Ocena",
"pt": "Classificação",
"ro": "Evaluare",
"ru": "Рейтинг",
"sk": "Hodnotenie",
"sl": "Ocena",
"sr": "Рејтинг",
"sw": "Rating",
"th": "การจัดอันดับ",
"tr": "Oy verin",
"cs": "Hodnocení",
"uk": "Рейтинг",
"vi": "Đánh giá",
"zh": "评分"
]
static var ratingTranslation: String {
let languages = preferredLanguages(Locale.preferredLanguages)
return ratingInPreferredLanguage(languages)
}
/**
Returns the word "Rating" in user's language.
- parameter language: ISO 639-1 language code. Example: 'en'.
*/
static func translation(_ language: String) -> String? {
return localizedRatings[language]
}
/**
Returns translation using the preferred language.
- parameter preferredLanguages: Array of preferred language codes (ISO 639-1). The first element is most preferred.
- parameter localizedText: Dictionary with translations for the languages. The keys are ISO 639-1 language codes and values are the text.
- parameter fallbackTranslation: The translation text used if no translation found for the preferred languages.
- returns: Translation for the preferred language.
*/
static func translationInPreferredLanguage(_ preferredLanguages: [String],
localizedText: [String: String],
fallbackTranslation: String) -> String {
for language in preferredLanguages {
if let translatedText = translation(language) {
return translatedText
}
}
return fallbackTranslation
}
static func ratingInPreferredLanguage(_ preferredLanguages: [String]) -> String {
return translationInPreferredLanguage(preferredLanguages,
localizedText: localizedRatings,
fallbackTranslation: defaultText)
}
static func preferredLanguages(_ preferredLocales: [String]) -> [String] {
return preferredLocales.map { element in
let dashSeparated = element.components(separatedBy: "-")
if dashSeparated.count > 1 { return dashSeparated[0] }
let underscoreSeparated = element.components(separatedBy: "_")
if underscoreSeparated.count > 1 { return underscoreSeparated[0] }
return element
}
}
}
// ----------------------------
//
// CosmosLayerHelper.swift
//
// ----------------------------
import UIKit
/// Helper class for creating CALayer objects.
class CosmosLayerHelper {
/**
Creates a text layer for the given text string and font.
- parameter text: The text shown in the layer.
- parameter font: The text font. It is also used to calculate the layer bounds.
- parameter color: Text color.
- returns: New text layer.
*/
class func createTextLayer(_ text: String, font: UIFont, color: UIColor) -> CATextLayer {
let size = NSString(string: text).size(withAttributes: [NSAttributedString.Key.font: font])
let layer = CATextLayer()
layer.bounds = CGRect(origin: CGPoint(), size: size)
layer.anchorPoint = CGPoint()
layer.string = text
layer.font = CGFont(font.fontName as CFString)
layer.fontSize = font.pointSize
layer.foregroundColor = color.cgColor
layer.contentsScale = UIScreen.main.scale
return layer
}
}
// ----------------------------
//
// CosmosTouch.swift
//
// ----------------------------
import UIKit
/**
Functions for working with touch input.
*/
struct CosmosTouch {
/**
Calculates the rating based on the touch location.
- parameter position: The horizontal location of the touch relative to the width of the stars.
- returns: The rating representing the touch location.
*/
static func touchRating(_ position: CGFloat, settings: CosmosSettings) -> Double {
var rating = preciseRating(
position: Double(position),
numberOfStars: settings.totalStars,
starSize: settings.starSize,
starMargin: settings.starMargin)
if settings.fillMode == .half {
rating += 0.20
}
if settings.fillMode == .full {
rating += 0.45
}
rating = CosmosRating.displayedRatingFromPreciseRating(rating,
fillMode: settings.fillMode, totalStars: settings.totalStars)
rating = max(settings.minTouchRating, rating) // Can't be less than min rating
return rating
}
/**
Returns the precise rating based on the touch position.
- parameter position: The horizontal location of the touch relative to the width of the stars.
- parameter numberOfStars: Total number of stars, filled and full.
- parameter starSize: The width of a star.
- parameter starSize: Margin between stars.
- returns: The precise rating.
*/
static func preciseRating(position: Double, numberOfStars: Int,
starSize: Double, starMargin: Double) -> Double {
if position < 0 { return 0 }
var positionRemainder = position;
// Calculate the number of times the star with a margin fits the position
// This will be the whole part of the rating
var rating: Double = Double(Int(position / (starSize + starMargin)))
// If rating is grater than total number of stars - return maximum rating
if Int(rating) > numberOfStars { return Double(numberOfStars) }
// Calculate what portion of the last star does the position correspond to
// This will be the added partial part of the rating
positionRemainder -= rating * (starSize + starMargin)
if positionRemainder > starSize
{
rating += 1
} else {
rating += positionRemainder / starSize
}
return rating
}
}
// ----------------------------
//
// CosmosRating.swift
//
// ----------------------------
import UIKit
/**
Helper functions for calculating rating.
*/
struct CosmosRating {
/**
Returns a decimal number between 0 and 1 describing the star fill level.
- parameter ratingRemainder: This value is passed from the loop that creates star layers. The value starts with the rating value and decremented by 1 when each star is created. For example, suppose we want to display rating of 3.5. When the first star is created the ratingRemainder parameter will be 3.5. For the second star it will be 2.5. Third: 1.5. Fourth: 0.5. Fifth: -0.5.
- parameter fillMode: Describe how stars should be filled: full, half or precise.
- returns: Decimal value between 0 and 1 describing the star fill level. 1 is a fully filled star. 0 is an empty star. 0.5 is a half-star.
*/
static func starFillLevel(ratingRemainder: Double, fillMode: StarFillMode) -> Double {
var result = ratingRemainder
if result > 1 { result = 1 }
if result < 0 { result = 0 }
return roundFillLevel(result, fillMode: fillMode)
}
/**
Rounds a single star's fill level according to the fill mode. "Full" mode returns 0 or 1 by using the standard decimal rounding. "Half" mode returns 0, 0.5 or 1 by rounding the decimal to closest of 3 values. "Precise" mode will return the fill level unchanged.
- parameter starFillLevel: Decimal number between 0 and 1 describing the star fill level.
- parameter fillMode: Fill mode that is used to round the fill level value.
- returns: The rounded fill level.
*/
static func roundFillLevel(_ starFillLevel: Double, fillMode: StarFillMode) -> Double {
switch fillMode {
case .full:
return Double(round(starFillLevel))
case .half:
return Double(round(starFillLevel * 2) / 2)
case .precise :
return starFillLevel
}
}
/**
Helper function for calculating the rating that is displayed to the user
taking into account the star fill mode. For example, if the fill mode is .half and precise rating is 4.6, the displayed rating will be 4.5. And if the fill mode is .full the displayed rating will be 5.
- parameter preciseRating: Precise rating value, like 4.8237
- parameter fillMode: Describe how stars should be filled: full, half or precise.
- parameter totalStars: Total number of stars.
- returns: Returns rating that is displayed to the user taking into account the star fill mode.
*/
static func displayedRatingFromPreciseRating(_ preciseRating: Double,
fillMode: StarFillMode, totalStars: Int) -> Double {
let starFloorNumber = floor(preciseRating)
let singleStarRemainder = preciseRating - starFloorNumber
var displayedRating = starFloorNumber + starFillLevel(
ratingRemainder: singleStarRemainder, fillMode: fillMode)
displayedRating = min(Double(totalStars), displayedRating) // Can't go bigger than number of stars
displayedRating = max(0, displayedRating) // Can't be less than zero
return displayedRating
}
/**
Returns the number of filled stars for given rating.
- parameter rating: The rating to be displayed.
- parameter totalNumberOfStars: Total number of stars.
- returns: Number of filled stars. If rating is biggen than the total number of stars (usually 5) it returns the maximum number of stars.
*/
static func numberOfFilledStars(_ rating: Double, totalNumberOfStars: Int) -> Double {
if rating > Double(totalNumberOfStars) { return Double(totalNumberOfStars) }
if rating < 0 { return 0 }
return rating
}
}
// ----------------------------
//
// CosmosSettings.swift
//
// ----------------------------
import UIKit
/**
Settings that define the appearance of the star rating views.