Converting CGPoints between UIKit and SpriteKit woes: UIViews next to SKNodes - ios

There are many posts on this but for whatever reason I can't seem to get the correct sequence of conversions correct. I'm trying to get the UISliders to go directly below the SKLabels.
As you can see in the pictures, one of the sliders doesn't show at all, and the other one is in the completely wrong place (the volume slider is near the seek label):
Here is my current attempt at getting this right, though I've tried a few other configurations that got me nowhere:
class GameScene: SKScene {
let seekSlider = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 15))
let volSlider = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 15))
override func didMove(to view: SKView) {
removeAllChildren() // Delete this in your actual project.
// Add some labels:
let seekLabel = SKLabelNode(text: "Seek")
seekLabel.setScale(3)
seekLabel.verticalAlignmentMode = .center
seekLabel.position = CGPoint(x: frame.minX + seekLabel.frame.width/2,
y: frame.maxY - seekLabel.frame.height)
let volLabel = SKLabelNode(text: "Volume")
volLabel.setScale(3)
volLabel.verticalAlignmentMode = .center
volLabel.position = CGPoint(x: frame.minX + volLabel.frame.width/2,
y: frame.minY + volLabel.frame.height + volSlider.frame.height)
/* CONVERSION WOES BELOW: */
// Configure sliders:
let seekOrigin = convertPoint(toView: convert(seekLabel.position, from: self))
seekSlider.frame = CGRect(origin: seekOrigin, size: CGSize(width: 200, height: 15))
seekSlider.value = 1
let volOrigin = convertPoint(fromView: CGPoint(x: volLabel.frame.minX, y: volLabel.frame.minY))
seekSlider.frame = CGRect(origin: volOrigin, size: CGSize(width: 200, height: 15))
seekSlider.value = 0
// Scene stuff:
view.addSubview(seekSlider)
view.addSubview(volSlider)
addChild(seekLabel)
addChild(volLabel)
}
}

You're very close! There are two minor issues in your code:
Issue #1
You modify the seekSlider's frame twice instead of modifying the seekSlider then the volSlider.
let volOrigin = convertPoint(fromView: CGPoint(x: volLabel.frame.minX, y: volLabel.frame.minY))
seekSlider.frame = CGRect(origin: volOrigin, size: CGSize(width: 200, height: 15))
seekSlider.value = 0
should be
let volOrigin = convertPoint(fromView: CGPoint(x: volLabel.frame.minX, y: volLabel.frame.minY))
volSlider.frame = CGRect(origin: volOrigin, size: CGSize(width: 200, height: 15))
volSlider.value = 0
Issue #2
The conversion code is not correct.
Using the convertPoint(toView method with the node's position should do the trick:
let seekOrigin = convertPoint(toView: seekLabel.position)
Final Code:
class GameScene: SKScene {
let seekSlider = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 15))
let volSlider = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 15))
override func didMove(to view: SKView) {
removeAllChildren() // Delete this in your actual project.
// Add some labels:
let seekLabel = SKLabelNode(text: "Seek")
seekLabel.setScale(3)
seekLabel.verticalAlignmentMode = .center
seekLabel.position = CGPoint(x: frame.minX + seekLabel.frame.width/2,
y: frame.maxY - seekLabel.frame.height)
let volLabel = SKLabelNode(text: "Volume")
volLabel.setScale(3)
volLabel.verticalAlignmentMode = .center
volLabel.position = CGPoint(x: frame.minX + volLabel.frame.width/2,
y: frame.minY + volLabel.frame.height + volSlider.frame.height)
// Configure sliders:
let seekOrigin = convertPoint(toView: seekLabel.position)
let offsetSeekOrigin = CGPoint(x: seekOrigin.x, y: seekOrigin.y + 50)
seekSlider.frame = CGRect(origin: offsetSeekOrigin, size: CGSize(width: 200, height: 15))
seekSlider.value = 1
let volOrigin = convertPoint(toView: volLabel.position)
let offsetVolOrigin = CGPoint(x: volOrigin.x, y: volOrigin.y - 50)
volSlider.frame = CGRect(origin: offsetVolOrigin, size: CGSize(width: 200, height: 15))
volSlider.value = 0
// Scene stuff:
view.addSubview(seekSlider)
view.addSubview(volSlider)
addChild(seekLabel)
addChild(volLabel)
}
}
Final Result:

Related

macOS NSScrollView Not Scrolling Vertically

I am trying to add few views to see if the NSScrollView will scroll vertically but it is not doing anything.
private func configure2() {
var yOffset = 0
let scrollView = NSScrollView(frame: NSRect(x: 0, y: 0, width: 400, height: 900))
scrollView.hasVerticalScroller = true
for _ in 1...20 {
let v = NSView(frame: NSRect(x: 0, y: 0 + yOffset, width: 50, height: 20))
v.wantsLayer = true
v.layer?.backgroundColor = NSColor.red.cgColor
scrollView.addSubview(v)
yOffset += 40
}
scrollView.backgroundColor = NSColor.green
self.addSubview(scrollView)
}
I remember in UIKit I can set the contentSize property of UIScrollView but in macOS I cannot set contentSize.
You need to set either the documentView or contentView of your NSScrollView. Then, you'll add your subviews to that view.
private func configure2() {
var yOffset = 0
let scrollView = NSScrollView(frame: NSRect(x: 0, y: 0, width: 400, height: 900))
let documentView = NSView(frame: .zero)
scrollView.hasVerticalScroller = true
for _ in 1...20 {
let v = NSView(frame: NSRect(x: 0, y: 0 + yOffset, width: 50, height: 20))
v.wantsLayer = true
v.layer?.backgroundColor = NSColor.red.cgColor
documentView.addSubview(v)
yOffset += 40
}
print(yOffset)
documentView.frame = .init(x: 0, y: 0, width: 400, height: yOffset)
scrollView.documentView = documentView
scrollView.backgroundColor = NSColor.green
self.addSubview(scrollView)
}

SpriteKit draw upside down text

In a playground, I am trying to make a SpriteKit scene with a top left origin going down (ie like a drawing program). Everything works except for text which is flipped. I need to make the text right side up. I am missing something. If I add the translate and scale, the text vanishes.
//: A SpriteKit based Playground
import PlaygroundSupport
import SpriteKit
class GameScene: SKScene
{
static let width = 1000
static let height = 1800
override func didMove(to view: SKView)
{
self.backgroundColor = SKColor.white
let cam = SKCameraNode()
self.camera = cam
cam.yScale = -1
let node = SKSpriteNode(color: SKColor.yellow, size: CGSize(width: 500, height: 300))
node.anchorPoint = CGPoint(x: 0, y: 0)
node.position = CGPoint(x: 10, y: 10)
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 200, height: 200))
let img = renderer.image { ctx in
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attrs = [NSAttributedStringKey.font: UIFont(name: "Futura", size: 72)!, NSAttributedStringKey.paragraphStyle: paragraphStyle]
//ctx.cgContext.translateBy(x: 0, y:200)
//ctx.cgContext.scaleBy(x: 0, y: -1)
let string = "Test"
string.draw(with: CGRect(x: 32, y: 32, width: 200, height: 200), options: .usesLineFragmentOrigin, attributes: attrs, context: nil)
}
let tex = SKTexture(image: img)
let zzz = SKSpriteNode(texture: tex)
zzz.anchorPoint = CGPoint(x: 0, y: 0)
zzz.position = CGPoint(x: 10, y: 10)
node.addChild(zzz)
// let z = SKSpriteNode(color: SKColor.red, size: CGSize(width: 200, height: 150))
// z.anchorPoint = CGPoint(x: 0, y: 0)
// z.position = CGPoint(x: 10, y: 10)
// node.addChild(z)
//
// let q = SKSpriteNode(color: SKColor.green, size: CGSize(width: 80, height: 70))
// q.anchorPoint = CGPoint(x: 0, y: 0)
// q.position = CGPoint(x: 10, y: 10)
// z.addChild(q)
self.addChild(node)
self.addChild(cam)
cam.position = CGPoint(x: GameScene.width/2, y: GameScene.height/2)
}
}
let sceneView = SKView(frame: CGRect(x:0 , y:0, width: 480, height: 640))
let scene = GameScene(size: CGSize(width: GameScene.width, height: GameScene.height))
scene.scaleMode = .aspectFit
sceneView.presentScene(scene)
PlaygroundSupport.PlaygroundPage.current.liveView = sceneView
Update:
ctx.cgContext.textMatrix = .identity
ctx.cgContext.translateBy(x: 0, y: 200)
ctx.cgContext.scaleBy(x: 1.0, y: -1.0)
now draws the text rightside up, but it is wrapped at 50% of the width
Final Update:
This worked, its rightsize up. The font size is proportional to the scene size (which is a dimension that fits on all iOS devices.
self.camera = cam
cam.yScale = -1
let boxSize = CGSize(width: 500, height: 500)
let node = SKSpriteNode(color: SKColor.yellow, size: boxSize)
node.anchorPoint = CGPoint(x: 0, y: 0)
node.position = CGPoint(x: 10, y: 10)
let renderer = UIGraphicsImageRenderer(size: boxSize)
let img = renderer.image { ctx in
let bounds = CGRect(x: 16, y: 0, width: boxSize.width-32, height: boxSize.height)
let string = "This is a long test with many lines."
let range = NSRange( location: 0, length: string.count)
guard let context = UIGraphicsGetCurrentContext() else { return }
let path = CGMutablePath()
path.addRect(bounds)
let attrString = NSMutableAttributedString(string: string)
attrString.addAttribute(NSAttributedStringKey.font, value: UIFont(name: "Futura", size: 84)!, range: range )
let framesetter = CTFramesetterCreateWithAttributedString(attrString as CFAttributedString)
let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attrString.length), path, nil)
CTFrameDraw(frame, context)
}
You should read https://www.raywenderlich.com/153591/core-text-tutorial-ios-making-magazine-app
CoreText inverts (technically, rotates) text in iOS. This is possibly because it is shared with MacOS which uses a different coordinate system. (Though why they couldn't fix this for iOS I have no idea).
Whatever the cause, you aren't doing anything wrong, iOS is doing the wrong thing. The simple solution (as per the linked article) is to simply rotate the text before drawing it.

Swift: Calling a function within a Core Graphics draw function

I'm trying to access a certain function which draws some lines using a UIBezierPath(). However, the usual process for accessing a nested function is not working, stating that the function is not a member.
To be specific, let's say class contains override func draw(_ rect: CGRect) which contains the desired func(). My goal is to execute func() from another class.
Thanks in advance!
Edit: Example Code:
import UIKit
import CoreGraphics
class figure: UIView {
override func draw(_ rect: CGRect) {
let circle = UIView(frame: CGRect(x: 560, y: 10.0, width: 100.0, height: 100.0))
circle.center = CGPoint(x: 560, y: 60)
circle.layer.cornerRadius = 50
circle.backgroundColor = UIColor.black
circle.clipsToBounds = true
let circle2 = UIView(frame: CGRect(x: 25.0, y: 25.0, width: 90.0, height: 90.0))
circle2.center = circle.center
circle2.layer.cornerRadius = 45
circle2.backgroundColor = UIColor.white
circle2.clipsToBounds = true
/*
var darkBlur = UIBlurEffect(style: UIBlurEffectStyle.dark)
var blurView = UIVisualEffectView(effect: darkBlur)
blurView.frame = circle.bounds
circle.addSubview(blurView)
*/
addSubview(circle)
addSubview(circle2)
let spine = UIView(frame: CGRect(x: 560, y: 110, width: 10, height: 110))
func spineDraw(){
spine.center = CGPoint(x: 560, y: 165)
spine.layer.cornerRadius = 5
spine.backgroundColor = UIColor.black
spine.clipsToBounds = true
addSubview(spine)
}
var shoulder = CGPoint(x: 400, y: 120)
var rElbow = CGPoint(x: 410 + rElbowXGlobal.rElbowX, y: 170 + rElbowYGlobal.rElbowY)
var rWrist = CGPoint(x: 410 + rWristXGlobal.rWristX, y: 195 + rWristYGlobal.rWristY)
let rArm = UIBezierPath()
rArm.lineWidth = 5
func rArmDraw() {
rArm.move(to: shoulder)
rArm.addLine(to: rElbow)
rArm.stroke()
rArm.addLine(to: rWrist)
rArm.stroke()
rArm.close()
}
var lElbow = CGPoint(x: 390 + lElbowXGlobal.lElbowX, y: 170 + lElbowYGlobal.lElbowY)
var lWrist = CGPoint(x: 390 + lWristXGlobal.lWristX, y: 195 + lWristYGlobal.lWristY)
let lArm = UIBezierPath()
lArm.lineWidth = 5
func lArmDraw(){
lArm.move(to: shoulder)
lArm.addLine(to: lElbow)
lArm.stroke()
lArm.addLine(to: lWrist)
lArm.stroke()
lArm.close()
}
var hip = CGPoint(x: 400, y: 215)
var rKnee = CGPoint(x: 410 + rKneeXGlobal.rKneeX, y: 250 + rKneeYGlobal.rKneeY)
var rAnkle = CGPoint(x: 410 + rAnkleXGlobal.rAnkleX, y: 270 + rAnkleYGlobal.rAnkleY)
let rLeg = UIBezierPath()
rLeg.lineWidth = 5
func rLegDraw(){
rLeg.move(to: hip)
rLeg.addLine(to: rKnee)
rLeg.stroke()
rLeg.addLine(to: rAnkle)
rLeg.stroke()
rLeg.close()
}
var lKnee = CGPoint(x: 390 + lKneeXGlobal.lKneeX, y: 250 + lKneeYGlobal.lKneeY)
var lAnkle = CGPoint(x: 390 + lAnkleXGlobal.lAnkleX, y: 270 + lAnkleYGlobal.lAnkleY)
let lLeg = UIBezierPath()
lLeg.lineWidth = 5
func lLegDraw(){
lLeg.move(to: hip)
lLeg.addLine(to: lKnee)
lLeg.stroke()
lLeg.addLine(to: lAnkle)
lLeg.stroke()
lLeg.close()
}
//debug grid
let path = UIBezierPath()
for i in 1...10 {
path.move(to: CGPoint(x: i*100, y: 0))
path.addLine(to: CGPoint(x: i*100, y: 1000))
path.stroke()
path.move(to: CGPoint(x: 0, y: i*100))
path.addLine(to: CGPoint(x: 2000, y: i*100))
}
spineDraw()
rArmDraw()
lArmDraw()
rLegDraw()
lLegDraw()
}
}
I am trying to execute the five functions at the bottom. I cannot execute anything within this class from another viewController class.

Dots following the path

I am looking for some simple method that will animate dots moving by closed path.
I have some path created with UIBezierPath. Which is represented by CAShapeLayer.
I want to place on this shape dots that will move around this closed path. The problem is that I couldn't find the best method. I do not want to add every dot programmatically. Maybe there is some method where could be use particles.
Path will have different shapes. The most important thing is to please dots with the same distance between each other.
I will be glad for help
Here is an example you can run in playground.
It's based on an article by Matt Long (from a while back) http://www.cimgf.com/2009/10/20/marching-ants-with-core-animation/
import UIKit
import PlaygroundSupport
let container = UIView(frame: CGRect(x: 0, y: 0, width: 600, height: 700))
container.backgroundColor = UIColor.green
let v = UIView(frame: CGRect(x: 100, y: 100, width: 300, height: 300))
v.backgroundColor = UIColor.yellow
let shp = CAShapeLayer()
shp.bounds = v.bounds
let pth = UIBezierPath()
pth.move(to: CGPoint(x: 20, y: 220))
pth.addLine(to: CGPoint(x: 20, y: 40))
pth.addLine(to: CGPoint(x: 40, y: 80))
pth.addLine(to: CGPoint(x: 120, y: 40))
pth.addLine(to: CGPoint(x: 140, y: 40))
pth.close()
shp.strokeColor = UIColor.orange.cgColor
shp.fillColor = UIColor.cyan.cgColor
shp.lineWidth = 3.0
shp.lineDashPattern = [5, 5]
shp.path = pth.cgPath
shp.position = CGPoint(x: 150, y: 150)
v.layer.addSublayer(shp)
container.addSubview(v)
let dashAnim = CABasicAnimation(keyPath: "lineDashPhase")
dashAnim.fromValue = 0
dashAnim.toValue = 15
dashAnim.duration = 0.75
dashAnim.repeatCount = 10000
shp.add(dashAnim, forKey: "lineDashPhase")
PlaygroundPage.current.liveView = container
PlaygroundPage.current.needsIndefiniteExecution = true

How to CGPath or SKShapeNode Rotation

I want to add rotated elliptical paths to one center point. Like image below but random rotated elliptical.
Draw these elliptical orbits with,
roadShape = SKShapeNode(ellipseInRect: centeredRect)
roadShape.strokeColor = UIColor.greenColor()
self.parent!.addChild(roadShape)
need to make small particles follow those elliptical orbits, thats why I need a path.
var followPath = SKAction.followPath(roadShape.path, asOffset: false, orientToPath: true, duration: 10);
particle.runAction(followPath)
I used SKShapeNode to draw and get the path property. But unfortunately SKShapeNode doesn't have any origin or anchorPoint property so I couldn't decent rotate to SKShapeNode. Do you have any suggestion to make it rotate or different way.
Thanks in advance.
let roadShape1 = SKShapeNode(ellipseInRect: CGRectMake(-100, -25, 200, 50))
roadShape1.strokeColor = UIColor.greenColor()
roadShape1.lineWidth = 3
roadShape1.position = CGPoint(x:frame.midX, y: frame.midY)
addChild(roadShape1)
let roadShape2 = SKShapeNode(ellipseInRect: CGRectMake(-100, -25, 200, 50))
roadShape2.strokeColor = UIColor.greenColor()
roadShape2.lineWidth = 3
let action2 = SKAction.rotateByAngle(CGFloat(M_PI)*0.75, duration:0)
roadShape2.runAction(action2)
roadShape2.position = CGPoint(x:frame.midX, y: frame.midY)
addChild(roadShape2)
let roadShape3 = SKShapeNode(ellipseInRect: CGRectMake(-100, -25, 200, 50))
roadShape3.strokeColor = UIColor.greenColor()
roadShape3.lineWidth = 3
let action3 = SKAction.rotateByAngle(CGFloat(M_PI)*0.25, duration:0)
roadShape3.runAction(action3)
roadShape3.position = CGPoint(x:frame.midX, y: frame.midY)
addChild(roadShape3)
You can also use applyTransform to apply the rotation to the bezierPath
instead of the SKShapeNode as follow:
let roadPath1 = UIBezierPath(ovalInRect: CGRect(x: -100, y: -25, width: 200, height: 50))
let roadPath2 = UIBezierPath(ovalInRect: CGRect(x: -100, y: -25, width: 200, height: 50))
roadPath2.applyTransform(CGAffineTransformMakeRotation(45.0 * CGFloat(M_PI) / 180))
let roadPath3 = UIBezierPath(ovalInRect: CGRect(x: -100, y: -25, width: 200, height: 50))
roadPath3.applyTransform(CGAffineTransformMakeRotation(135.0 * CGFloat(M_PI) / 180))
let roadShape1 = SKShapeNode(ellipseInRect: CGRectMake(-100, -25, 200, 50))
roadShape1.path = roadPath1.CGPath
roadPath1.stroke()
roadShape1.lineWidth = 3
roadShape1.position = CGPoint(x:frame.midX, y: frame.midY)
addChild(roadShape1)
let roadShape2 = SKShapeNode(ellipseInRect: CGRectMake(-100, -25, 200, 50))
roadShape2.path = roadPath2.CGPath
roadPath2.stroke()
roadShape2.lineWidth = 3
roadShape2.position = CGPoint(x:frame.midX, y: frame.midY)
addChild(roadShape2)
let roadShape3 = SKShapeNode(ellipseInRect: CGRectMake(-100, -25, 200, 50))
roadShape3.path = roadPath3.CGPath
roadPath3.stroke()
roadShape3.lineWidth = 3
roadShape3.position = CGPoint(x:frame.midX, y: frame.midY)
addChild(roadShape3)

Resources