This is a simple control which maps touches within its bounds to a 0.0 - 1.0 range on the horizontal and vertical axes, returned as a CIVector.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TouchCaptureControl: UIControl { | |
var value: CIVector = CIVector(x: 0.0, y: 0.0) | |
@IBInspectable var horizontalMinimumValue: CGFloat = 0.0 | |
@IBInspectable var horizontalMaximumValue: CGFloat = 1.0 | |
@IBInspectable var verticalMinimumValue: CGFloat = 0.0 | |
@IBInspectable var verticalMaximumValue: CGFloat = 1.0 | |
@IBInspectable var flipHorizontalAxis: Bool = false | |
@IBInspectable var flipVerticalAxis: Bool = false | |
//MARK: - Value Translation | |
func setValueForPoint(point: CGPoint) { | |
var normalizedX = point.x / bounds.width | |
if flipHorizontalAxis { normalizedX = 1.0 - normalizedX } | |
var normalizedY = point.y / bounds.height | |
if flipVerticalAxis { normalizedY = 1.0 - normalizedY } | |
let mappedX = (horizontalMaximumValue - horizontalMinimumValue) * normalizedX + horizontalMinimumValue | |
let mappedY = (verticalMaximumValue - verticalMinimumValue) * normalizedY + verticalMinimumValue | |
let newValue = CIVector(x: mappedX, y: mappedY) | |
if newValue != value { | |
value = newValue | |
sendActionsForControlEvents(.ValueChanged) | |
} | |
} | |
//MARK: - Touches | |
override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool { | |
setValueForPoint(touch.locationInView(self)) | |
return super.beginTrackingWithTouch(touch, withEvent: event) | |
} | |
override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool { | |
setValueForPoint(touch.locationInView(self)) | |
return super.continueTrackingWithTouch(touch, withEvent: event) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment