iPhone calculate numbers between 0-50 for custom slider - ios

I want to calculate numbers between 0 to 50 when user move on the slider right and left. I am using a formula such as but didn't succedded.
(point.x + 100) / 20
Where point.x is a CGPoint getting with locatioOfView: method between two UIView's
CGPoint point = [sender locationInView:self.viewBaseSlider];
Note : Here self.viewBaseSlider is not a slider it is a Custom View.
Any ideas?

You have to translate location from range between 0 to your-custom-view-width to range from 0 to your-slider-max (50 in this case).
Here's my take on it in swift:
let maxPoints = 50
let customViewWidth = customView.frame.size.width
let pointWidth = Float(customViewWidth) / Float(maxPoints)
if let touch = touches.first {
let location = touch.location(in: customView)
let point = Int(roundf(Float(location.x) / pointWidth))
print("Selected \(point)")
}
And here's working example, where grey area is customView and output in console comes from clicking in the start, around the middle and the end of the grey region:

Related

Why do I get an error when trying to move the mouse?

I want to control the position of the mouse by adding the offset value to the current position. But I have a problem getting the y of the current position. Why?
This is my code:
func moveTouch(offsetPosition: CGPoint) {
let cursortPosition = NSEvent.mouseLocation
let resultPosition = CGPoint(x: cursortPosition.x + offsetPosition.x, y: cursortPosition.y + offsetPosition.y)
CGDisplayMoveCursorToPoint(1, resultPosition)
let source = CGEventSource.init(stateID: .hidSystemState)
let eventDown = CGEvent(mouseEventSource: source, mouseType: .mouseMoved, mouseCursorPosition: resultPosition , mouseButton: .left)
eventDown?.post(tap: .cghidEventTap)
print("===> cursort:\(cursortPosition) result:\(resultPosition) position:\(offsetPosition)")
}
ok, I know! because Because the position obtained by NSEvent.mouseLocation is based on the lower left corner。 And setting the position of CGWarpMouseCursorPosition is based on the lower left corner

how to detect difference between 2 points on the map and consider the zoom?

I am using a map with some annotations, I want to group the nearest annotations in annotation group to not overlap in the design in case of user zoom out, but my problem is to how to know the distance between annotations and this distance should change when zooming in and out.
the distance should be between points with x and y formate note meters
So my question is to how to catch the difference between 2 points on the map and consider the zoom
// convert location to cLLocation
let cLLocation1 = CLLocation(latitude: post1Location?.lat ?? 0, longitude: post1Location?.lng ?? 0)
let cLLocation2 = CLLocation(latitude: post2Location?.lat ?? 0, longitude: post2Location?.lng ?? 0)
// this is return the dinsactence in metres but i don't need that
let distance = cLLocation1.distance(from: cLLocation2)
let annotaionPoint1 = MKMapPoint(cLLocation1.coordinate)
let annotaionPoint2 = MKMapPoint(cLLocation2.coordinate)
let xDistance = max(annotaionPoint1.x, annotaionPoint2.x) - min(annotaionPoint1.x, annotaionPoint2.x)
let yDistance = max(annotaionPoint1.y, annotaionPoint2.y) - min(annotaionPoint1.y, annotaionPoint2.y)
this is working but zoom in and zoom out no effect so I need zoom to make change
if min(xDistance, yDistance) <= 32 {
/// action
}

Calculate bearing in MKMapView gives wrong value while crossing 180 meridian

I need to draw lines to demonstrate transportation of goods on apple maps. To clarify start- and end-point, I draw a little arrowhead on the destination side.The arrowhead is drawn separately but it is reversed in one case.
>-->-->-->-
instead of
<--<--<--<-
I am using MKMapView and MKPolyline to draw lines. I am using MKOverlay to add direction arrows. The steps I follow are,
calculate bearing of
Source : CLLocationCoordinate2D(latitude: -33.8392932, longitude: 151.21519799999999)
Destination: CLLocationCoordinate2D(latitude: 39.645516999999998, longitude: -104.598724)
using the following function
open static func getDirectionOf( _ supplyLineWithCoordinates: [CLLocationCoordinate2D]) -> CGFloat {
guard let sourceCoordniate = supplyLineWithCoordinates.first,
let destinationCoordniate = supplyLineWithCoordinates.last else {
fatalError("Coordinates of supply line not found")
}
let sourcePoint: MKMapPoint = MKMapPointForCoordinate(sourceCoordniate)
let destinationPoint: MKMapPoint = MKMapPointForCoordinate(destinationCoordniate)
let x: Double = destinationPoint.x - sourcePoint.x
let y: Double = destinationPoint.y - sourcePoint.y
var arrowDirection = CGFloat(fmod(atan2(y, x), 360.0))
if arrowDirection < 0.0 {
arrowDirection += 2 * .pi
}
return arrowDirection
}
Rotate the arrow image and add it as the map overlay. The directions are calculated correctly in most of the cases, however, when I select the line shown below the direction is displayed 180 opposite. It starts from Sydney, Australia and ends in Denver, US
When trying to display the region with this two locations in mapView.setVisibleMapRect these region is not displayed, mapview tries to display region starting from Sydney (Australia) to Denver(US) through Asia and Europe, while it should display the map area I have attached above. If you have suggestions for optimisation, feel free to mention it.
I think this might be the reason, the direction should be calculated along the red line but it being calculated along the green line. Both lines are drawn by connecting same location coordinates in map. Any known workaround for this?
I solved it in a dirty way by converting coordinate to CGPoint and then calculating bearing between Points.
let destinationPoint = mapView.convert(destination, toPointTo: nil)
let sourcePoint = mapView.convert(source, toPointTo: nil)
let bearing = atan2(sourcePoint.y - destinationPoint.y, sourcePoint.x - destinationPoint.x) - .pi
Caution: This calculation will go wrong when map is rotated

How can i check if two SKSpriteNodes are near each other?

How can i check if two SKSpriteNodes are near each other? like in a radius of 100. i am using the gamescene.swift and gamescene.sks.
SKSpriteNode has a position property with the (x, y).
Distance between two positions is sqrt((x1-x2)^2 + (y1-y2)^2)
So:
let dist = sqrt(pow(sk1.position.x - sk2.position.x, 2.0) + pow(sk1.position.y - sk2.position.y, 2.0))
if dist < 100 {
// they are close
}
This is center to center.
Based on #MartinR's comment, you could also
let dist = hypot(sk1.position.x - sk2.position.x, sk1.position.y - sk2.position.y)
Which does the distance function for you.
If you want to use built in SKPhysicsBody, then just set the body to a circle with radius of 100, then you can use the didBeginContact method when a contact occurs:
func setup()
{
let physicsBody1 = SKPhysicsBody(circleOfRadius:100.0)
physicsBody1.categoryBitMask = 1
physicsBody1.collisionBitMask = 0
physicsBody1.contactTestBitMask = 2
sprite1.physicsBody = physicsBody1
let physicsBody2 = SKPhysicsBody(circleOfRadius:100.0)
physicsBody2.categoryBitMask = 2
physicsBody2.collisionBitMask = 0
physicsBody2.contactTestBitMask = 1
sprite2.physicsBody = physicsBody2
}
func didBeginContact(contact:SKPhysicsContact)
{
//find some tutorials to your liking, and do your contact code here
}

Swift - Jigsaw Snap to Place

So I am developing an Ipad app that allows the user to solve a jigsaw puzzle. I've worked out getting the panning motion for each piece, but getting them where I want to has not worked properly. I am trying to make a piece snap into it's final destination when it's within a small range, which is followed by a clicking sound.
Here is a bit of code for a single puzzle piece. When my new game button is pressed, an Image View gets set to the corresponding picture, and randomly placed on the canvas.
#IBAction func NewGameTapped(sender: UIButton){
let bounds = UIScreen.mainScreen().bounds
let height = bounds.size.height
let width = bounds.size.width
image1.image = UIImage(named:"puzzleImage1.png")
image1.center.x = CGFloat(100 + arc4random_uniform(UInt32(width)-300))
image1.center.y = CGFloat(100 + arc4random_uniform(UInt32(height)-300))
//Create Panning (Dragging) Gesture Recognizer for Image View 1
let panRecognizer1 = UIPanGestureRecognizer(target: self, action: "handlePanning1:")
// Add Panning (Dragging) Gesture Recognizer to Image View 1
image1.addGestureRecognizer(panRecognizer1)
}
This is where I am having some issues.
func handlePanning1(recognizer: UIPanGestureRecognizer) {
let center = dict1_image_coordinates["puzzleImage1"] as![Int]
let newTranslation: CGPoint = recognizer.translationInView(image1)
recognizer.view?.transform = CGAffineTransformMakeTranslation(lastTranslation1.x + newTranslation.x, lastTranslation1.y + newTranslation.y)
if recognizer.state == UIGestureRecognizerState.Ended {
lastTranslation1.x += newTranslation.x
lastTranslation1.y += newTranslation.y
}
checkPosition(image1, center: center)
}
func checkPosition(image: UIImageView, center: [Int]){
let distance: Double = sqrt(pow((Double(image.center.x) - Double(center[0])),2) + pow((Double(image.center.y) - Double(center[1])),2))
//if the distance is within range, set image to new location.
if distance <= 20{
image.center.x = CGFloat(center[0])
image.center.y = CGFloat(center[1])
AudioServicesPlaySystemSound(clickSoundID)
}
For whatever reason, the puzzle piece only wants to snap to it's spot when the piece begins the game within the acceptable snap distance. I have tried checking for the object position in various different parts of my program, but nothing has worked so far. Any help or other tips are greatly appreciated.
The issue is likely caused by this line
image1.addGestureRecognizer(panRecognizer1)
Usually people add gestureRecognizer on the parentView, or the rootView of the view controller instead of the image1 itself. The benefit is that the parentView never moves, where as the image1 is constantly being transformed, which may or may not affect the recognizer.translationInView(x) method return value.
do this instead:
self.view.addGestureRecognizer(panRecognizer1)
and change to this line in handlePanning1 function:
image1.transform = CGAffineTransformMakeTranslation(lastTranslation1.x + newTranslation.x, lastTranslation1.y + newTranslation.y)

Resources