@@ -46,6 +46,13 @@ public class MSCircularSliderHandle: CALayer {
4646 }
4747 }
4848
49+ /** Specifies whether or not the handle should rotate to always point outwards - *default: false* */
50+ internal var isRotatable : Bool = false {
51+ didSet {
52+ setNeedsDisplay ( )
53+ }
54+ }
55+
4956 /** The handle's color - *default: .darkGray* */
5057 internal var color : UIColor = . darkGray {
5158 didSet {
@@ -123,8 +130,13 @@ public class MSCircularSliderHandle: CALayer {
123130 y: center ( ) . y - diameter * 0.5 ,
124131 width: diameter,
125132 height: diameter)
126- image? . draw ( in: frame)
127-
133+ if isRotatable {
134+ let rotatedImg = imageRotated ( img: image!, byDegrees: angle)
135+ rotatedImg. draw ( in: frame)
136+ }
137+ else {
138+ image? . draw ( in: frame)
139+ }
128140 }
129141 else if handleType == . doubleCircle {
130142 calculatedHandleColor. withAlphaComponent ( isHighlightable && isPressed ? 0.9 : 1.0 ) . set ( )
@@ -159,4 +171,41 @@ public class MSCircularSliderHandle: CALayer {
159171 return point. x >= center ( ) . x - handleRadius && point. x <= center ( ) . x + handleRadius && point. y >= center ( ) . y - handleRadius && point. y <= center ( ) . y + handleRadius
160172 }
161173
174+ /** Converts degrees to radians */
175+ private func toRad( _ degrees: Double ) -> Double {
176+ return ( ( Double . pi * degrees) / 180.0 )
177+ }
178+
179+ /** Converts radians to degrees */
180+ private func toDeg( _ radians: Double ) -> Double {
181+ return ( ( 180.0 * radians) / Double. pi)
182+ }
183+
184+ /** Rotates a given image by the specified degrees */
185+ private func imageRotated( img: UIImage , byDegrees degrees: CGFloat ) -> UIImage {
186+
187+ // calculate the size of the rotated view's containing box for our drawing space
188+ let rotatedViewBox = UIView ( frame: CGRect ( origin: CGPoint . zero, size: img. size) )
189+ let t = CGAffineTransform ( rotationAngle: CGFloat ( toRad ( Double ( degrees) ) ) )
190+ rotatedViewBox. transform = t
191+ let rotatedSize = rotatedViewBox. frame. size
192+
193+ // Create the bitmap context
194+ UIGraphicsBeginImageContext ( rotatedSize)
195+ let bitmap = UIGraphicsGetCurrentContext ( )
196+
197+ // Move the origin to the middle of the image so we will rotate and scale around the center.
198+ bitmap? . translateBy ( x: rotatedSize. width / 2.0 , y: rotatedSize. height / 2.0 )
199+
200+ // // Rotate the image context
201+ bitmap? . rotate ( by: CGFloat ( toRad ( Double ( degrees) ) ) ) ;
202+
203+ // Now, draw the rotated/scaled image into the context
204+ bitmap? . draw ( img. cgImage!, in: CGRect ( x: - img. size. width / 2 , y: - img. size. height / 2 , width: img. size. width, height: img. size. height) )
205+
206+ let newImage = UIGraphicsGetImageFromCurrentImageContext ( )
207+ UIGraphicsEndImageContext ( )
208+
209+ return newImage!
210+ }
162211}
0 commit comments