Where is CGRectGetMidX/Y in Swift 3

 ̄綄美尐妖づ 提交于 2019-12-12 09:29:50

问题


IN Siwft 3, I could not find CGRectGetMidX and Y which I used to calclate position of nodes. Also I could not find CGPointMake. IN this case, how am I able to set nodes in the center of SKScene?

Thanks!

Update: I created a node and specified the position of it, by writing this way;

let node = SKSpriteNode()
node.position = CGPoint(x:self.frame.size.width/2, y:self.frame.size.height/2)
node.size = CGSize(width: 100, height: 100)
node.color = SKColor.red
self.addChild(node)

Why is it somewhere else like different place from the specified location? I firstly thought there was a change in Swift3 and the depresciation of CGPointMake caused this problem, but it does not seem like it is the cause. In this case, is the use of CGRect better? It is very helpful if you could write code that fixs this position issue. Again, thank you for your help.


回答1:


In Swift you shouldn't use those old style notations. Just use the constructors and properties:

let point = CGPoint(x: 1, y: 2)
let rect = CGRect(x: 1, y: 2, width: 3, height: 4)
let mx = rect.midX



回答2:


C global functions like CGRectGetMidX/Y, CGPointMake, etc. shouldn't be used in Swift (they're deprecated in Swift 2.2, removed in Swift 3).

Swift imports CGRect and CGPoint as native types, with initializers, instance methods, etc. They're much more natural to use, and they don't pollute the global name space as the C functions once did.

let point = CGPoint(x: 0, y: 0) //replacement of CGPointMake

let rect = CGRect(x: 0, y: 0, width: 5, height: 5) //replacement of CGRectMake

let midX = rect.midX //replacement of CGRectGetMidX
let midY = rect.midY //replacement of CGRectGetMidY

Their respect API reference is linked above. You might also find the CoreGraphics API reference handy too.




回答3:


Have too many center calculations in your code. Use this.

extension CGRect {
        var center : CGPoint  {
            get {
            return CGPoint(x:self.midX, y: self.midY)
            }
        }
    }


来源:https://stackoverflow.com/questions/40035825/where-is-cgrectgetmidx-y-in-swift-3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!