The app I am developing(using Xcode 9 and swift 4) requires the user to move through the map in hybrid flyover mode. I have achieved that much, but I want to permanently change the angle (so they can see buildings and statues) as the navigate through the map. As of right now they can see the map from directly overhead and have the adjust angles manually. below is the code I have used so far
let distance: CLLocationDistance = 650
let pitch: CGFloat = 65
let heading = 0.0
var camera: MKMapCamera?
override func viewDidLoad() {
super.viewDidLoad()
mapView.mapType = .satelliteFlyover
let coordinate = CLLocationCoordinate2D(latitude: 40.7484405,
`enter code here` longitude: -73.9856644)
camera = MKMapCamera(lookingAtCenter: coordinate,
fromDistance: distance,
pitch: pitch,
heading: `enter code here`heading)
mapView.camera = camera!
}
#IBAction func animateCamera(_ sender: AnyObject) {
}
Related
In Project -A- I used GPUImageView to display Video (recorded on greenscreen) with transparency. Using the GPUImageChromaKeyBlendFilter, and so on.
and works Superb.
Another project -B- based on ARKIT shows me in the space a plain with VIDEO and it also works fine using SKVideoNode and AVPlayer.
Now the question is to combine it all together in one :) So in space I want to display Video but with transparency ...
Unfortunately, I can not render a GPUImageView on any SpriteKit element, and then add to SKScene, which is an animated texture for SCNPlane, is it possible at all? Or maybe there is other way to render Video with transparencies with ARKit.?
Thx for any suggestions
I had the same task! See my solution here.
I basically implemented ChromaKeyMaterial from Lësha Turkowski and wrote this code to place and play the video.
import UIKit
import ARKit
class ARTransVC: UIViewController{
#IBOutlet weak var arSceneView: ARSCNView!
let configuration = ARWorldTrackingConfiguration()
private var player: AVPlayer = {
guard let url = Bundle.main.url(forResource: "FY3A4278", withExtension: "mp4") else { fatalError() }
return AVPlayer(url: url)
}()
override func viewDidLoad() {
super.viewDidLoad()
self.arSceneView.debugOptions = [ARSCNDebugOptions.showWorldOrigin, ARSCNDebugOptions.showFeaturePoints]
self.arSceneView.session.run(configuration)
//a delay for ARKit to capture the surroundings
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
// A SpriteKit scene to contain the SpriteKit video node
let spriteKitScene = SKScene(size: CGSize(width: self.arSceneView.frame.width, height: self.arSceneView.frame.height))
spriteKitScene.scaleMode = .aspectFit
spriteKitScene.backgroundColor = .clear
spriteKitScene.scaleMode = .aspectFit
//Create the SpriteKit video node, containing the video player
let videoSpriteKitNode = SKVideoNode(avPlayer: self.player)
videoSpriteKitNode.position = CGPoint(x: spriteKitScene.size.width / 2.0, y: spriteKitScene.size.height / 2.0)
videoSpriteKitNode.size = spriteKitScene.size
videoSpriteKitNode.yScale = -1.0
videoSpriteKitNode.play()
spriteKitScene.addChild(videoSpriteKitNode)
// To make the video loop
self.player.actionAtItemEnd = .none
NotificationCenter.default.addObserver(
self,
selector: #selector(ARTransVC.playerItemDidReachEnd),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: self.player.currentItem)
// Create the SceneKit scene
let scene = SCNScene()
self.arSceneView.scene = scene
//Create a SceneKit plane and add the SpriteKit scene as its material
let background = SCNPlane(width: CGFloat(1), height: CGFloat(1))
background.firstMaterial?.diffuse.contents = spriteKitScene
let chromaKeyMaterial = ChromaKeyMaterial()
chromaKeyMaterial.diffuse.contents = self.player
let backgroundNode = SCNNode(geometry: background)
backgroundNode.geometry?.firstMaterial?.isDoubleSided = true
backgroundNode.geometry!.materials = [chromaKeyMaterial]
backgroundNode.position = SCNVector3(0,0,-2.0)
scene.rootNode.addChildNode(backgroundNode)
//video does not start without delaying the player
//playing the video before just results in [SceneKit] Error: Cannot get pixel buffer (CVPixelBufferRef)
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.player.seek(to:CMTimeMakeWithSeconds(1, 1000))
self.player.play()
}
}
}
#objc func playerItemDidReachEnd(notification: NSNotification) {
if let playerItem: AVPlayerItem = notification.object as? AVPlayerItem {
playerItem.seek(to: kCMTimeZero, completionHandler: nil)
}
}
What I want to achieve:
Display small, variable sized svgs in my app with auto layout.
The svgs contain pre-rendered latex formulas. The svgs are loaded asynchronously so I don't know upfront which size or aspect ratio they are.
The hardest pre-conditions I could imagine.
I tried several svg displaying libraries, and no one turned out to work with our svgs, so I decided to use a UIWebView.
The problem here is, that the svgs should not be scrollable and the UIWebView of minimal size.
The svgs should span all available width and have a height based on the aspect ratio.
What I tried:
class FormulaView: UIView, UIWebViewDelegate, XMLParserDelegate {
private var view: UIView!
#IBOutlet weak var webView: UIWebView!
#IBOutlet weak var topMargin: NSLayoutConstraint!
#IBOutlet weak var bottomMargin: NSLayoutConstraint!
private var width = -1.0
private var height = -1.0
// MARK: Initialisation
override init(frame: CGRect) {
super.init(frame: frame)
setUpView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setUpView()
}
// MARK: Set Up
// Performs the initial setup.
// Loads a XIB file into a view and returns this view.
func loadSVG(fromURL url: URL) {
let request = NSURLRequest(url: url)
webView.delegate = self
webView.loadRequest(request as URLRequest)
}
func loadSVG(fromString string: String) {
let url = URL(string: string)
if url == nil {
self.isHidden = true
return
}
self.loadSVG(fromURL: url!)
}
var tableView: UITableView?
private func viewFromNibForClass() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
return view
}
private func setUpView() {
view = viewFromNibForClass()
view.frame = bounds
// Auto-layout stuff.
view.autoresizingMask = [
UIViewAutoresizing.flexibleWidth,
UIViewAutoresizing.flexibleHeight
]
addSubview(view)
// Formula should take no space if no formula is loaded
topMargin.constant = 0
bottomMargin.constant = 0
self.translatesAutoresizingMaskIntoConstraints = false
self.addConstraints([
NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal,
toItem: view, attribute: .top, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal,
toItem: view, attribute: .right, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal,
toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal,
toItem: view, attribute: .left, multiplier: 1.0, constant: 0)
])
}
// MARK: - UIWebView delegate
func webViewDidFinishLoad(_ webView: UIWebView) {
// Get xml of svg file
let xml = webView.stringByEvaluatingJavaScript(from: "document.documentElement.outerHTML")
let parser = XMLParser(data: (xml?.data(using: .utf8))!)
parser.delegate = self
parser.parse()
}
// MARK: - XMLParser delegate
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
// Get width and height of svg
if elementName == "svg" {
self.height = Double(attributeDict["height"]?
.replacingOccurrences(of: "pt", with: "") ?? "")
?? -1.0
self.width = Double(attributeDict["width"]?
.replacingOccurrences(of: "pt", with: "") ?? "")
?? -1.0
let aspectRatio = self.width / self.height
tableView?.beginUpdates()
// Calculate height the webview should have based on the width and the normal aspect ratio of the svg
let webviewHeight = self.webView.bounds.size.width / CGFloat(aspectRatio)
if let constraint = (webView.constraints.filter {
$0.firstAttribute == .height && $0.secondAttribute == .notAnAttribute
}.first) {
constraint.constant = webviewHeight
} else {
webView.heightAnchor.constraint(equalToConstant: webviewHeight).isActive = true
}
// Apply a 24 margin as a svg is now loaded
topMargin.constant = 24
bottomMargin.constant = 24
tableView?.endUpdates()
self.layoutIfNeeded()
self.invalidateIntrinsicContentSize()
// Zoom webview appropriately that the svg is completely visible and no scrolling is neccessary or even possible
let scrollView = webView.scrollView
let zoom = webView.bounds.size.width / scrollView.contentSize.width
scrollView.maximumZoomScale = zoom
scrollView.setZoomScale(zoom, animated: true) // Error occurs here
// prevent scrolling
scrollView.isScrollEnabled = false
scrollView.isPagingEnabled = false
scrollView.isUserInteractionEnabled = false
scrollView.isDirectionalLockEnabled = true
}
}
}
This version seems to work fine as I tested it on the simulator,
but in some cases (EDIT: I only see these crashes in our Bug reporting tool), I get an error (CALayerInvalidGeometry: CALayer position contains NaN: [nan nan]) at this line scrollView.setZoomScale(zoom, animated: true).
It seems the calculating the zoom results in CGFloat.nan,
(1) but when does this occur,
(2) how can I prevent this and
(3) if it occurs, how can I calculate the zoom in these cases?
EDIT: Or in other words, why are webView.bounds.size.width and/or scrollView.contentSize.width non positiv values?
If I could reproduce it, I could say more, but unluckily I can't...
Thanks in advance,
Dennis
I have been trying to get the Map coordinates from my QML map with the MouseArea. But the problem is that I only get the coordinates of my mouse. It tells me the coordinates where the position of my mouse is on the window but not the coordinates of the click I made on the actual map. I don't know how to explain it better. Here is a part of my code:
MouseArea{
id: mouseArea
property var positionInRoot: mapFromItem(myItem, mouseX, mouseY)
anchors.fill: parent
acceptedButtons: Qt.LeftButton
hoverEnabled: true
onClicked: {
console.warn("Coordinates: " + mouseArea.positionInRoot)
}
}
My Question is now if it's possible to get the coordinates of the map where I made a mouseclick? And if yes how could I do it?
You should use the toCoordinate method of the QML map.
mapFromItem / mapToItem are used to map a point in a item to another item's coordinate system, but we're talking about QML Item's (x, y) and not QtPosition latitude, longitude. You still need those however, if your MouseArea and Map do not have the same x/y position
Here is an example that display a label with lat and lon under the mouse cursor.
Map {
id: map
anchors.fill: parent
plugin: mapPlugin
}
MouseArea
{
anchors.fill: map
hoverEnabled: true
property var coordinate: map.toCoordinate(Qt.point(mouseX, mouseY))
Label
{
x: parent.mouseX - width
y: parent.mouseY - height - 5
text: "lat: %1; lon:%2".arg(parent.coordinate.latitude).arg(parent.coordinate.longitude)
}
}
If you want to display coordinates in degrees minutes second format, you could use helper such as these:
function decimalToMinutes(value, isLat)
{
var letter = isLat?value>=0?"N":"S":value>=0?"E":"W"
var degrees = Math.floor(value)
var minutes = Math.floor((value-degrees)*60)
var seconds = ((value-degrees)*3600 - 60*minutes).toFixed(1)
return "%1° %2' %3\" %4".arg(degrees).arg(minutes).arg(seconds).arg(letter)
}
function minutesToDecimal(value)
{
var myRegexp = /(\d+)° (\d+)' (\d+(?:\.\d+)?)" ([NSEW])/g;
var match = myRegexp.exec(value)
if(match == null)
return 0
return ((match[4]=="N"||match[4]=="E")?1:-1)*(Number(match[1]) +Number( match[2]/60) + Number(match[3]/3600))
}
function coordinateToString(coordinate)
{
return decimalToMinutes(coordinate.latitude, true) + " " + decimalToMinutes(coordinate.longitude, false)
}
I'm having trouble drawing polylines, and I think I've deduced it to being an issue with iOS 11 beta 4. It was working yesterday with the same code, and now I've updated to beta 4 and it doesn't draw polylines.
Just confirmed this by trying it in Xcode 8 on iOS 10.3 simulator, and in Xcode 9b4 on the iOS 11b4 simulator.
Code:
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
let mapView = MKMapView()
override func viewDidLoad() {
super.viewDidLoad()
mapView.frame = CGRect(x: 10, y: 10, width: 300, height: 300)
mapView.delegate = self
mapView.region = MKCoordinateRegionMake(CLLocationCoordinate2D(latitude: 51.482736, longitude: -0.015253), MKCoordinateSpanMake(0.005, 0.005))
mapView.delegate = self
let coordinate1 = CLLocationCoordinate2D(latitude: 51.482736, longitude: -0.015253)
let coordinate2 = CLLocationCoordinate2D(latitude: 51.482736, longitude: -0.016253)
let polyline = MKPolyline(coordinates: [coordinate1, coordinate2], count: 2)
mapView.add(polyline, level: .aboveLabels)
view.addSubview(mapView)
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor.red
renderer.lineWidth = 4.0
return renderer
}
}
iOS 10:
iOS 11:
Annotations are added to the map without issue.
Fixed in beta 5. We just had to wait.
I am trying to make a horizontally scrolling menu in my new Sprite Kit game. With Sprite Kit being fairly new, there aren't many good tutorials for Sprite Kit. Is UIScrollView compatible with Sprite Kit? I have tried a couple of ways such as this:
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
scroll.pagingEnabled = YES;
NSInteger numberOfViews = 3;
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i * self.view.frame.size.width;
UIView *awesomeView = [[UIView alloc] initWithFrame:CGRectMake(xOrigin, 0, self.view.frame.size.width, self.view.frame.size.height)];
awesomeView.backgroundColor = [UIColor colorWithRed:0.5/i green:0.5 blue:0.5 alpha:1];
[scroll addSubview:awesomeView];
}
This didn't work. I have never worked with UIScrollView before. Can anyone give a way of making a horizontally scrolling menu using UIScrollView? An example of what I am trying to do is in Bloons TD 5 with their menu.
I know this question is a few months old already, but I was also looking for a scrolling menu slider to select levels in my SpriteKit game. I couldn't find any code already existing and the thought of force fitting the UIScrollView into my SpriteKit game didn't appeal to me. So I wrote my own sliding menu for level selection.
I've simulated all of the motions of the UIScrollView so it looks natural, and can be configured to scroll left - right or up - down.
As a bonus I created a parallax background on the menu which can be easily swapped out with new images for a custom look.
https://github.com/hsilived/ScrollingMenu
The code for the Scrolling menu is very well commented so there shouldn't be to many integration issues.
The github project has a fully working demo with Worlds, Levels and parallax images. If you like it mark my answer as useful so I can gain some reputation :)
You can definitely combine UIKit controls with SpriteKit. From the SKScene where you want to have a UIScrollView add the scroll view to self.view, like this: [self.view addSubview:scroll]. You may want to do this in the -(void)didMoveToView:(SKView*)view method on your SKScene. Remember to remove the scroll view from the SKView once you transition out of the SKScene that is using it. You can do that in the -(void)willMoveFromView:(SKView*)view method. Don't forget to set the contentSize on the UIScrollView.
Note: If you want to have SpriteKit nodes over the UIKit controls then you will need to write your own SKSpriteNode that behaves like a UIScrollView.
Expanding on Note: If your scroll view needs to contain Sprite-kit nodes and not just UIKit views you won't be able to use UIScrollView unless you do something clever as suggested in the answer to this question here
There are many ways to obtain it, through SKCameraNode, using UIKit elements like UIScrollView or other ways..
But I want to show you how to do it simple with SpriteKit only.
Conceptually, you should build a larger SKNode that containt every single voice of your menu where each element have an equal distance from the other.
You can simulate the scrolling with an SKAction that move our node to the center of the nearest visible element.
GameViewController:
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
guard let view = self.view as! SKView? else { return }
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
view.showsPhysics = false
view.showsDrawCount = true
let scene = GameScene(size:view.bounds.size)
scene.scaleMode = .aspectFill
view.presentScene(scene)
}
}
GameScene:
class GameScene: SKScene {
var lastX: CGFloat = 0.0
var moveableArea = SKNode() // the larger SKNode
var worlds: [String]! = ["world1","world2","world3"] // the menu voices
var currentWorld:Int = 0 // contain the current visible menu voice index
var worldsPos = [CGPoint]() // an array of CGPoints to store the menu voices positions
override func didMove(to view: SKView) {
//Make a generic title
let topLabel = SKLabelNode.init(text: "select world")
topLabel.fontSize = 40.0
self.addChild(topLabel)
topLabel.zPosition = 1
topLabel.position = CGPoint(x:frame.width / 2, y:frame.height*0.80)
// Prepare movable area
self.addChild(moveableArea)
moveableArea.position = CGPoint(x:self.frame.midX,y:self.frame.midY)
// Prepare worlds:
for i in 0..<worlds.count {
// add a title for i^ world
let worldLabel = SKLabelNode.init(text: worlds[i])
self.moveableArea.addChild(worldLabel)
worldLabel.position = CGPoint(x:CGFloat(i)*self.frame.width ,y:moveableArea.frame.height*0.60)
// add a sprite for i^ world
let randomRed = CGFloat(drand48())
let randomGreen = CGFloat(drand48())
let randomBlue = CGFloat(drand48())
let randomColor = UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
let worldSprite = SKSpriteNode.init(color: randomColor, size: CGSize.init(width: 100.0, height: 100.0))
worldSprite.name = worlds[i]
self.moveableArea.addChild(worldSprite)
worldSprite.position = CGPoint(x:CGFloat(i)*self.frame.width ,y:0.0)
}
}
func tapNode(node:SKNode,action:SKAction) {
if node.action(forKey: "tap") == nil {
node.run(action, withKey: "tap")
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first!
let location = touch.location(in: self)
let touchedNode = self.atPoint(location)
lastX = location.x
let sequence = SKAction.sequence([SKAction.scale(to: 1.5, duration: 0.2),SKAction.scale(to: 1.0, duration: 0.1)]) // a little action to show the selection of the world
switch touchedNode.name {
case "world1"?:
print("world1 was touched..")
tapNode(node:touchedNode,action:sequence)
case "world2"?:
print("world2 was touched..")
tapNode(node:touchedNode,action:sequence)
case "world3"?:
print("world3 was touched..")
tapNode(node:touchedNode,action:sequence)
default:break
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first!
let location = touch.location(in: self)
let currentX = location.x
let leftLimit:CGFloat = CGFloat(worlds.count-1)
let rightLimit:CGFloat = 1.0
let scrollSpeed:CGFloat = 1.0
let newX = moveableArea.position.x + ((currentX - lastX)*scrollSpeed)
if newX < self.size.width*(-leftLimit) {
moveableArea.position = CGPoint(x:self.size.width*(-leftLimit), y:moveableArea.position.y)
}
else if newX > self.size.width*rightLimit {
moveableArea.position = CGPoint(x:self.size.width*rightLimit, y:moveableArea.position.y)
}
else {
moveableArea.position = CGPoint(x:newX, y:moveableArea.position.y)
}
// detect current visible world
worldsPos = [CGPoint]()
for i in 0..<worlds.count {
let leftLimit = self.size.width-(self.size.width*CGFloat(i))
let rightLimit = self.size.width-(self.size.width*CGFloat(i+1))
if rightLimit ... leftLimit ~= moveableArea.position.x {
currentWorld = i
}
worldsPos.append(CGPoint(x: (rightLimit + (leftLimit - rightLimit)/2), y:moveableArea.position.y))
}
lastX = currentX
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if worldsPos.count>0, moveableArea.action(forKey: "moveAction") == nil {
let moveAction = SKAction.move(to: worldsPos[currentWorld], duration: 0.5)
moveAction.timingMode = .easeInEaseOut
self.moveableArea.run(moveAction, withKey: "moveAction")
}
}
}
As you can see , with touchesBegan we can detect the touched world and select it, with touchesMoved we are able to move the moveable node to the correct position and to detect the nearest visible world and with touchesEnded we can create the smooth scrolling to automatic move to the current nearest visible voice after a touch..
Output: